import fs from 'node:fs';
import path from 'node:path';
import crypto from 'node:crypto';
import readline from 'node:readline/promises';
import { stdin as input, stdout as output } from 'node:process';
import { fileURLToPath } from 'node:url';

const ROOT = path.resolve(path.dirname(fileURLToPath(import.meta.url)), '..');
const rl = readline.createInterface({ input, output });

function sanitize(value) {
  return String(value).replace(/[\r\n]/g, '').trim();
}
function quote(value) {
  return `"${String(value).replace(/\\/g, '\\\\').replace(/"/g, '\\"')}"`;
}

console.log('\nMarloth Park Central - PayPal Production Setup\n');
console.log('This wizard creates the private .env configuration. No source file editing is required.\n');

const paypalEnv = sanitize((await rl.question('PayPal mode [sandbox/live] (live): ')) || 'live').toLowerCase();
if (!['sandbox', 'live'].includes(paypalEnv)) throw new Error('PayPal mode must be sandbox or live.');
const baseUrlRaw = sanitize(await rl.question('Public HTTPS website URL (example: https://guide.example.com): '));
if (!/^https:\/\/[A-Za-z0-9.-]+(?::\d+)?$/.test(baseUrlRaw)) throw new Error('A valid HTTPS base URL is required. Do not include a trailing slash or path.');
const parsed = new URL(baseUrlRaw);
const clientId = sanitize(await rl.question(`PayPal ${paypalEnv} Client ID: `));
const clientSecret = sanitize(await rl.question(`PayPal ${paypalEnv} Secret: `));
const webhookId = sanitize(await rl.question(`PayPal ${paypalEnv} Webhook ID: `));
if (!clientId || !clientSecret || !webhookId) throw new Error('Client ID, Secret and Webhook ID are required.');
const supportEmail = sanitize((await rl.question('Support email (contact@marlothparkcentral.com): ')) || 'contact@marlothparkcentral.com');
const supportWhatsApp = sanitize((await rl.question('Support WhatsApp (+27 79 084 1496): ')) || '+27 79 084 1496');
const downloadMinutes = sanitize((await rl.question('One-time download expiry in minutes (30): ')) || '30');
if (!/^\d+$/.test(downloadMinutes) || Number(downloadMinutes) < 5) throw new Error('Download expiry must be at least 5 minutes.');
const adminKey = crypto.randomBytes(32).toString('base64url');

const env = [
  'NODE_ENV=production',
  'PORT=3000',
  `BASE_URL=${quote(baseUrlRaw)}`,
  `DOMAIN=${quote(parsed.hostname)}`,
  'TRUST_PROXY=true',
  `PAYPAL_ENV=${paypalEnv}`,
  `PAYPAL_CLIENT_ID=${quote(clientId)}`,
  `PAYPAL_CLIENT_SECRET=${quote(clientSecret)}`,
  `PAYPAL_WEBHOOK_ID=${quote(webhookId)}`,
  `DOWNLOAD_TOKEN_MINUTES=${downloadMinutes}`,
  `SUPPORT_EMAIL=${quote(supportEmail)}`,
  `SUPPORT_WHATSAPP=${quote(supportWhatsApp)}`,
  `ADMIN_API_KEY=${quote(adminKey)}`,
  'DB_PATH=/app/data/orders.sqlite',
  ''
].join('\n');

const envPath = path.join(ROOT, '.env');
fs.writeFileSync(envPath, env, { mode: 0o600 });
try { fs.chmodSync(envPath, 0o600); } catch {}
rl.close();

console.log('\nConfiguration saved securely.');
console.log(`Webhook URL: ${baseUrlRaw}/api/paypal/webhook`);
console.log('Subscribe this webhook to:');
console.log('  PAYMENT.CAPTURE.COMPLETED');
console.log('  PAYMENT.CAPTURE.DENIED');
console.log('  PAYMENT.CAPTURE.REFUNDED');
console.log('  PAYMENT.CAPTURE.REVERSED');
console.log(`\nAdmin support key (also saved in .env): ${adminKey}`);
console.log('\nNext command: npm run preflight\n');
