const fs = require('fs');
const path = require('path');

const express = require('express');
var app = express();

function parseDomains() {
  try {
    const ris = {
      domains: JSON.parse(process.env.DOMAINS || '[]'),
      domainsAllowed: JSON.parse(process.env.DOMAINS_ALLOWED || '[]'),
    };
    return ris;
  } catch {
    return { domains: [], domainsAllowed: [] };
  }
}

function buildAllowedOrigins(domains, domainsAllowed, isProduction) {
  if (!isProduction) {
    return [
      'https://localhost:3000',
      'https://localhost:8089',
      'https://localhost:8082',
      'https://localhost:8083',
      'https://localhost:8084',
      'https://localhost:8085',
      'https://localhost:8088',
      'https://localhost:8099',
      'https://localhost:8094',
      'https://192.168.8.182',
      'https://192.168.8.182:8084/',
      'http://192.168.8.182:8084/',
    ];
  }

  const baseOrigins = domains.flatMap((domain) => [
    `https://${domain.hostname}`,
    `https://api.${domain.hostname}`,
    `https://test.${domain.hostname}`,
    `https://testapi.${domain.hostname}`,
    `http://${domain.hostname}`,
    `http://api.${domain.hostname}`,
    `http://test.${domain.hostname}`,
    `http://testapi.${domain.hostname}`,
  ]);

  console.log('baseOrigins:', baseOrigins.map((origin) => `'${origin}'`).join(', '));

  const allowedExtra = domainsAllowed.flatMap((domain) => [`https://${domain}`, `http://${domain}`]);

  return [...baseOrigins, ...allowedExtra];
}

function createCorsOptions(domains, domainsAllowed, isProduction, noCors = false) {
  if (noCors) {
    console.log('NOCORS mode enabled');
    return {
      exposedHeaders: ['x-auth', 'x-refrtok', 'x-browser-random'],
    };
  }

  const allowedOrigins = buildAllowedOrigins(domains, domainsAllowed, isProduction);

  console.log('allowedOrigins:', allowedOrigins.map((origin) => `'${origin}'`).join(', '));

  let originValidator = (origin, callback) => {
    if (!origin) {
      // console.log('✅ Origin undefined or empty — allowing');
      return callback(null, true);
    }

    if (typeof origin !== 'string' || !/^https?:\/\/[^\s/$.?#].[^\s]*$/.test(origin)) {
      console.error('❌ Invalid origin:', origin);
      return callback(new Error('Origine non valida'), false);
    }

    if (allowedOrigins.includes(origin)) {
      return callback(null, true);
    }

    console.warn('❌ Origin blocked:', origin);
    return callback(new Error('CORS non permesso per questa origine'), false);
  };

  if (app.get('env') === 'development') {
    originValidator = (_origin, callback) => callback(null, true);
  }

  return {
    origin: originValidator,
    credentials: true,
    methods: ['GET', 'POST', 'PUT', 'DELETE', 'OPTIONS', 'PATCH'],
    allowedHeaders: ['Origin', 'X-Requested-With', 'Content-Type', 'Accept', 'Authorization', 'x-auth', 'x-refrtok', 'x-browser-random'],
    exposedHeaders: ['x-auth', 'x-refrtok', 'x-browser-random'],
    maxAge: 86400,
    preflightContinue: false,
    optionsSuccessStatus: 204,
  };
}

async function getCredentials(hostname) {
  const key = fs.readFileSync(`/etc/letsencrypt/live/${hostname}/${process.env.PATH_CERT_KEY}`, 'utf8');
  const cert = fs.readFileSync(`/etc/letsencrypt/live/${hostname}/${process.env.PATH_SERVER_CRT}`, 'utf8');
  return {
    key,
    cert,
    secureProtocol: 'TLSv1_2_method',
    secureOptions: require('constants').SSL_OP_NO_SSLv3 | require('constants').SSL_OP_NO_TLSv1,
  };
}

module.exports = { parseDomains, createCorsOptions, getCredentials };
