import fs from 'node:fs';
import path from 'node:path';
import { fileURLToPath } from 'node:url';
import { config, ROOT, validateRuntimeConfig } from '../src/config.js';
import { getAccessToken } from '../src/paypal.js';

const results = [];
function check(name, ok, detail = '') {
  results.push({ name, ok, detail });
  console.log(`${ok ? 'PASS' : 'FAIL'}  ${name}${detail ? ` - ${detail}` : ''}`);
}

console.log('\nMPC sales landing page preflight\n');
try { validateRuntimeConfig(); check('Runtime configuration', true, `${config.paypalEnv} / ${config.baseUrl}`); }
catch (error) { check('Runtime configuration', false, error.message); }
{ const [major, minor] = process.versions.node.split('.').map(Number); check('Node.js version', major > 22 || (major === 22 && minor >= 5), process.versions.node); }
check('Protected companion PDF', fs.existsSync(config.product.filePath), config.product.filePath);
if (fs.existsSync(config.product.filePath)) check('Companion PDF size', fs.statSync(config.product.filePath).size > 1_000_000, `${(fs.statSync(config.product.filePath).size/1024/1024).toFixed(1)} MB`);
check('Landing page', fs.existsSync(path.join(ROOT, 'public', 'index.html')));
check('HTTPS public URL', config.baseUrl.startsWith('https://'), config.baseUrl);
check('PayPal webhook ID', Boolean(config.paypalWebhookId));
try {
  if (config.paypalEnv !== 'mock') {
    const token = await getAccessToken();
    check('PayPal OAuth connection', Boolean(token), `${config.paypalEnv} credentials accepted`);
  }
} catch (error) { check('PayPal OAuth connection', false, error.message); }
try {
  fs.mkdirSync(path.dirname(config.dbPath), { recursive: true });
  fs.accessSync(path.dirname(config.dbPath), fs.constants.W_OK);
  check('Database directory writable', true, path.dirname(config.dbPath));
} catch (error) { check('Database directory writable', false, error.message); }

const failed = results.filter((item) => !item.ok);
console.log(`\n${failed.length ? 'Preflight failed.' : 'Preflight passed.'} ${results.length - failed.length}/${results.length} checks passed.\n`);
if (failed.length) process.exit(1);
