const fs = require('fs');
const path = require('path');
const http = require('http');
const https = require('https');
const tools = require('../tools/general');
const { setupExpress } = require('./setupExpress');
const { setupRouters } = require('./setupRouters');

const { setupWebSocket } = require('./setupWebSocket');
const { setupCronJobs } = require('./cronJobs');
const { parseDomains, createCorsOptions, getCredentials } = require('./serverUtils');
const { setupMailchimpRoutes } = require('./setupRouters');

async function myLoad() {
  return tools.loadApps();
}

async function startServer(app, port) {
  const isProduction = ['production', 'test'].includes(process.env.NODE_ENV);
  const { domains, domainsAllowed } = parseDomains();
  const corsOptions = createCorsOptions(domains, domainsAllowed, isProduction);

  let server;

  await myLoad().then(async (ris) => {
    setupExpress(app, corsOptions);
    const ok = setupRouters(app);

    if (!ok) {
      console.error('Errore durante setupRouters');
      process.exit(1);
    }
    setupMailchimpRoutes(app);

    console.log('DOMAINS:', domains)
    console.log(domains.map(({ hostname, port }) => `${hostname}:${port}`).join(', '));
    console.table(domains);

    // 👇 logica migliorata per gestire HTTPS anche in dev
    if (isProduction) {
      await createHttpsServers(domains, app);
    } else if (process.env.HTTPS_LOCALHOST === 'true') {
      server = await createHttpsLocalServer(app, port);
    } else {
      server = await createHttpServer(app, port);
    }
    setupWebSocket(server);
    setupCronJobs();
  });

  return server;
}

async function createHttpsServers(domains, app) {
  console.log('NUMERO DOMINI:', domains.length);
  for (const d of domains) {
    console.log('.  DOMINIO: ', d.hostname + ' ...');
    const credentials = await getCredentials(d.hostname);
    const server = https.createServer(credentials, app);
    server.listen(d.port, () => {
      console.log(`⭐️ HTTPS ${d.hostname} server running on port ${d.port}`)
    });
  }
}

// ✅ nuova funzione: HTTPS per localhost
async function createHttpsLocalServer(app, port) {
  try {
    const keyPath = path.resolve(`./${process.env.PATH_CERT_KEY}`);
    const certPath = path.resolve(`./${process.env.PATH_SERVER_CRT}`);
    const key = fs.readFileSync(keyPath, 'utf8');
    const cert = fs.readFileSync(certPath, 'utf8');

    const credentials = {
      key,
      cert,
      ciphers:
        'ECDHE-RSA-AES256-GCM-SHA384:ECDHE-RSA-AES128-GCM-SHA256:ECDHE-RSA-AES128-SHA:ECDHE-RSA-AES128-SHA256:ECDHE-RSA-AES256-SHA:ECDHE-RSA-AES256-SHA384',
      honorCipherOrder: true,
      secureProtocol: 'TLSv1_2_method',
    };

    const httpsServer = https.createServer(credentials, app);
    httpsServer.listen(port, '0.0.0.0', () => {
      console.log(`⭐️ HTTPS LOCALHOST server attivo sulla porta ${port}`);
    });
    return httpsServer;
  } catch (error) {
    console.error('❌ Errore caricamento certificati HTTPS locali:', error.message);
    console.log('➡️ Avvio fallback HTTP');
    return createHttpServer(app, port);
  }
}

async function createHttpServer(app, port) {
  const server = http.createServer(app);
  server.listen(port, () => console.log(`⭐️ HTTP server su porta ${port}`));
  return server;
}

module.exports = { startServer };
