import fs from 'node:fs';
import path from 'node:path';
import { fileURLToPath } from 'node:url';

const __filename = fileURLToPath(import.meta.url);
const __dirname = path.dirname(__filename);
export const ROOT = path.resolve(__dirname, '..');

function loadEnvFile(filePath) {
  if (!fs.existsSync(filePath)) return;
  const lines = fs.readFileSync(filePath, 'utf8').split(/\r?\n/);
  for (const raw of lines) {
    const line = raw.trim();
    if (!line || line.startsWith('#')) continue;
    const equals = line.indexOf('=');
    if (equals < 1) continue;
    const key = line.slice(0, equals).trim();
    let value = line.slice(equals + 1).trim();
    if ((value.startsWith('"') && value.endsWith('"')) || (value.startsWith("'") && value.endsWith("'"))) value = value.slice(1, -1);
    if (process.env[key] === undefined) process.env[key] = value.replace(/\\n/g, '\n');
  }
}
loadEnvFile(path.join(ROOT, '.env'));

function integer(name, fallback) {
  const value = Number.parseInt(process.env[name] ?? String(fallback), 10);
  if (!Number.isFinite(value) || value < 1) throw new Error(`Invalid integer environment variable: ${name}`);
  return value;
}

export const config = {
  nodeEnv: process.env.NODE_ENV || 'production',
  port: integer('PORT', 3000),
  baseUrl: (process.env.BASE_URL || 'http://localhost:3000').replace(/\/$/, ''),
  trustProxy: process.env.TRUST_PROXY === 'true',
  paypalEnv: process.env.PAYPAL_ENV || 'sandbox',
  paypalClientId: process.env.PAYPAL_CLIENT_ID || '',
  paypalClientSecret: process.env.PAYPAL_CLIENT_SECRET || '',
  paypalWebhookId: process.env.PAYPAL_WEBHOOK_ID || '',
  allowMockPayPal: process.env.ALLOW_MOCK_PAYPAL === 'true',
  product: {
    name: 'First Time Marloth & Kruger International Visitors Companion',
    sku: 'MPC-COMPANION-V1',
    currency: 'USD',
    price: '14.99',
    compareAt: '29.00',
    filePath: path.join(ROOT, 'private', 'First-Time-Marloth-Kruger-International-Visitors-Companion-V1.0.pdf'),
    downloadName: 'First-Time-Marloth-Kruger-International-Visitors-Companion-V1.0.pdf'
  },
  dbPath: process.env.DB_PATH || path.join(ROOT, 'data', 'orders.sqlite'),
  downloadTokenMinutes: integer('DOWNLOAD_TOKEN_MINUTES', 30),
  supportEmail: process.env.SUPPORT_EMAIL || 'contact@marlothparkcentral.com',
  supportWhatsApp: process.env.SUPPORT_WHATSAPP || '+27 79 084 1496',
  adminApiKey: process.env.ADMIN_API_KEY || ''
};

export function validateRuntimeConfig() {
  if (config.paypalEnv === 'mock') {
    if (config.nodeEnv === 'production' && !config.allowMockPayPal) {
      throw new Error('PAYPAL_ENV=mock is blocked in production. Use sandbox/live, or set ALLOW_MOCK_PAYPAL=true only for controlled QA.');
    }
    return;
  }
  if (!['sandbox', 'live'].includes(config.paypalEnv)) throw new Error('PAYPAL_ENV must be sandbox, live, or mock.');
  if (!config.paypalClientId) throw new Error('Missing PAYPAL_CLIENT_ID.');
  if (!config.paypalClientSecret) throw new Error('Missing PAYPAL_CLIENT_SECRET.');
  if (config.nodeEnv === 'production' && !config.baseUrl.startsWith('https://')) throw new Error('BASE_URL must use HTTPS in production.');
}
