// server/index.ts
import express from "express";
import { createServer } from "http";
import path2 from "path";
import { fileURLToPath as fileURLToPath2 } from "url";
import nodemailer from "nodemailer";

// server/pricing.ts
import xlsx from "xlsx";
import path from "path";
import { fileURLToPath } from "url";
var __filename = fileURLToPath(import.meta.url);
var __dirname = path.dirname(__filename);
var EDAD_BRACKETS = [0, 5, 18, 20, 22, 25, 28, 30, 32, 35, 38, 40, 42, 45, 48, 50, 52, 55, 58, 60, 62, 65, 70, 80];
var factorMap = /* @__PURE__ */ new Map();
var deptsByPlan = /* @__PURE__ */ new Map();
var epsByPlan = /* @__PURE__ */ new Map();
var knownDepts = /* @__PURE__ */ new Set();
var knownEps = /* @__PURE__ */ new Set();
var axaPriceMap = /* @__PURE__ */ new Map();
var axaPlanIds = /* @__PURE__ */ new Set();
var planInfo = /* @__PURE__ */ new Map();
function resolveEdad(edad) {
  const clamped = Math.min(Math.max(edad, EDAD_BRACKETS[0]), EDAD_BRACKETS[EDAD_BRACKETS.length - 1]);
  let best = EDAD_BRACKETS[0];
  for (const b of EDAD_BRACKETS) {
    if (b <= clamped) best = b;
    else break;
  }
  return best;
}
function loadPricingData(dbPath) {
  const filePath = dbPath ?? path.resolve(__dirname, "../database2.2.xlsx");
  factorMap.clear();
  deptsByPlan.clear();
  epsByPlan.clear();
  knownDepts.clear();
  knownEps.clear();
  planInfo.clear();
  axaPriceMap.clear();
  axaPlanIds.clear();
  console.log("\u{1F4CA} Cargando base de datos de tarifas...");
  const wb = xlsx.readFile(filePath, { dense: true });
  const ws = wb.Sheets[wb.SheetNames[0]];
  const rows = xlsx.utils.sheet_to_json(ws, { header: 1, raw: true, defval: null });
  let loaded = 0;
  for (let i = 1; i < rows.length; i++) {
    const row = rows[i];
    if (!row || row[1] == null) continue;
    const planId = Number(row[1]);
    const nombre = String(row[2] ?? "");
    const aseg = String(row[3] ?? "");
    const edad = Number(row[4]);
    const genero = String(row[5] ?? "");
    const depto = String(row[6] ?? "");
    const eps = String(row[7] ?? "");
    const precioBase = Number(row[8]);
    const factor = Number(row[9]);
    const precioAxa = row[13] != null ? Number(row[13]) : null;
    const fKey = `${planId}_${edad}`;
    if (!factorMap.has(fKey)) factorMap.set(fKey, factor);
    if (precioAxa != null && precioAxa > 0) {
      const esFem = genero.toLowerCase().includes("fem") || genero.toLowerCase().includes("muj");
      const gKey = esFem ? "F" : "M";
      axaPriceMap.set(`${planId}_${edad}_${gKey}`, precioAxa);
      axaPlanIds.add(planId);
    }
    if (!planInfo.has(planId)) {
      planInfo.set(planId, { planId, aseguradora: aseg, nombre, precioBase });
    }
    if (!deptsByPlan.has(planId)) deptsByPlan.set(planId, /* @__PURE__ */ new Set());
    deptsByPlan.get(planId).add(depto);
    if (depto !== "Todos" && depto !== "Todas") knownDepts.add(depto);
    if (!epsByPlan.has(planId)) epsByPlan.set(planId, /* @__PURE__ */ new Set());
    epsByPlan.get(planId).add(eps);
    if (eps !== "Todos" && eps !== "Todas") knownEps.add(eps);
    loaded++;
  }
  console.log(`\u2705 ${loaded} tarifas cargadas para ${planInfo.size} planes`);
  console.log(`   AXA Colpatria: ${axaPlanIds.size} planes con precio especial (${axaPriceMap.size} entradas)`);
  console.log(`   Edades: ${EDAD_BRACKETS.join(", ")}`);
}
function getPrice(planId, edad, genero, _departamento, _eps) {
  if (axaPlanIds.has(planId)) {
    const edadBracket2 = resolveEdad(edad);
    const esFemenino = genero.toLowerCase().includes("fem") || genero.toLowerCase().includes("muj");
    const gKey = esFemenino ? "F" : "M";
    const axaPrice = axaPriceMap.get(`${planId}_${edadBracket2}_${gKey}`);
    if (axaPrice != null) return axaPrice;
  }
  const info = planInfo.get(planId);
  if (!info) return null;
  const edadBracket = resolveEdad(edad);
  const factor = factorMap.get(`${planId}_${edadBracket}`);
  if (factor == null) return null;
  return Math.round(info.precioBase * factor);
}
function isPlanAvailable(planId, departamento, eps) {
  if (axaPlanIds.has(planId)) return true;
  const deptos = deptsByPlan.get(planId);
  const epsSet = epsByPlan.get(planId);
  if (!deptos || !epsSet) return false;
  const planEsNacional = deptos.has("Todos") || deptos.has("Todas");
  if (planEsNacional) return true;
  const deptOk = !departamento || !knownDepts.has(departamento) || deptos.has(departamento);
  const epsOk = !eps || epsSet.has("Todos") || epsSet.has("Todas") || !knownEps.has(eps) || epsSet.has(eps);
  return deptOk && epsOk;
}
function getAllPlans() {
  return [...planInfo.values()].sort((a, b) => a.planId - b.planId);
}
function getAllDepts() {
  const all = /* @__PURE__ */ new Set();
  for (const set of deptsByPlan.values())
    for (const d of set) if (d !== "Todos" && d !== "Todas") all.add(d);
  return [...all].sort();
}
function getAllEps() {
  const all = /* @__PURE__ */ new Set();
  for (const set of epsByPlan.values())
    for (const e of set) if (e !== "Todos" && e !== "Todas") all.add(e);
  return [...all].sort();
}

// server/index.ts
var __filename2 = fileURLToPath2(import.meta.url);
var __dirname2 = path2.dirname(__filename2);
try {
  process.loadEnvFile(path2.join(__dirname2, ".env"));
} catch {
}
var MAIL_TO = process.env.MAIL_TO || "info@evaseguro.com";
var NOTIFY = [...new Set(
  `${MAIL_TO},info@evaseguro.com,segurosevai2@gmail.com`.split(",").map((s) => s.trim().toLowerCase()).filter(Boolean)
)].join(",");
var MAIL_FROM = process.env.MAIL_FROM || process.env.SMTP_USER || "info@evaseguro.com";
var SMTP_PORT = Number(process.env.SMTP_PORT || 587);
var transporter = nodemailer.createTransport({
  host: process.env.SMTP_HOST || "smtp.gmail.com",
  port: SMTP_PORT,
  secure: SMTP_PORT === 465,
  // true para SSL (465), false para TLS (587)
  auth: {
    user: process.env.SMTP_USER || "",
    pass: process.env.SMTP_PASS || ""
  }
});
try {
  loadPricingData();
} catch (err) {
  console.warn("\u26A0\uFE0F  No se pudo cargar database2.xlsx:", err.message);
}
async function startServer() {
  const app = express();
  const server = createServer(app);
  app.use(express.json());
  app.get("/api/precio", (req, res) => {
    const planId = Number(req.query.planId);
    const edad = Number(req.query.edad);
    const genero = String(req.query.genero || "Masculino");
    const depto = String(req.query.departamento || "");
    const eps = String(req.query.eps || "");
    if (!planId || req.query.edad == null || req.query.edad === "") {
      res.status(400).json({ error: "planId y edad son obligatorios" });
      return;
    }
    const precio = getPrice(planId, edad, genero, depto, eps);
    const disponible = isPlanAvailable(planId, depto, eps);
    res.json({ planId, precio, disponible, edad, genero, departamento: depto, eps });
  });
  app.post("/api/precios-lote", (req, res) => {
    const { planIds, edad, genero, departamento, eps } = req.body;
    if (!Array.isArray(planIds) || edad == null) {
      res.status(400).json({ error: "planIds y edad son obligatorios" });
      return;
    }
    const resultados = {};
    for (const planId of planIds) {
      resultados[planId] = {
        precio: getPrice(planId, edad, genero, departamento, eps),
        disponible: isPlanAvailable(planId, departamento, eps)
      };
    }
    res.json({ resultados, edad, genero, departamento, eps });
  });
  app.get("/api/filtros", (_req, res) => {
    res.json({
      departamentos: getAllDepts(),
      eps: getAllEps(),
      planes: getAllPlans()
    });
  });
  app.post("/api/cotizar", async (req, res) => {
    const { nombre, telefono, correo, afiliado, tipo } = req.body;
    if (!nombre || !telefono || !correo) {
      res.status(400).json({ error: "Campos obligatorios faltantes" });
      return;
    }
    const subject = `[EvaCare] Nueva cotizaci\xF3n${tipo ? ` - ${tipo}` : ""} de ${nombre}`;
    const html = `
      <div style="font-family:Arial,sans-serif;max-width:600px;margin:0 auto">
        <div style="background:#0B1D34;padding:24px;border-radius:12px 12px 0 0">
          <h2 style="color:#00C5D4;margin:0">Nueva cotizaci\xF3n recibida</h2>
          ${tipo ? `<p style="color:#fff;margin:4px 0 0;font-size:14px">${tipo}</p>` : ""}
        </div>
        <div style="border:1px solid #eee;border-top:none;padding:24px;border-radius:0 0 12px 12px">
          <table style="width:100%;border-collapse:collapse">
            <tr><td style="padding:8px 0;color:#666;font-size:14px;width:180px">Nombre completo</td>
                <td style="padding:8px 0;font-weight:600">${nombre}</td></tr>
            <tr style="background:#f9f9f9"><td style="padding:8px 0;color:#666;font-size:14px">Tel\xE9fono / WhatsApp</td>
                <td style="padding:8px 0;font-weight:600">${telefono}</td></tr>
            <tr><td style="padding:8px 0;color:#666;font-size:14px">Correo corporativo</td>
                <td style="padding:8px 0;font-weight:600">${correo}</td></tr>
            <tr style="background:#f9f9f9"><td style="padding:8px 0;color:#666;font-size:14px">\xBFAfiliado a ARL?</td>
                <td style="padding:8px 0;font-weight:600">${afiliado || "No indic\xF3"}</td></tr>
          </table>
          <p style="margin-top:24px;padding:12px;background:#E0F7FA;border-radius:8px;font-size:13px;color:#00838F">
            Este cliente solicit\xF3 una cotizaci\xF3n desde <strong>EvaCare</strong>. Resp\xF3ndele en menos de 24 horas.
          </p>
        </div>
      </div>
    `;
    try {
      if (!process.env.SMTP_USER || !process.env.SMTP_PASS) {
        console.log("\u{1F4E7} [COTIZACI\xD3N SIN SMTP \u2014 configura .env]", { nombre, telefono, correo, afiliado, tipo });
        res.json({ ok: true, warning: "SMTP no configurado \u2014 datos registrados en consola" });
        return;
      }
      await transporter.sendMail({
        from: `"EvaCare Seguros" <${MAIL_FROM}>`,
        to: NOTIFY,
        replyTo: correo,
        subject,
        html
      });
      console.log(`\u2705 Correo enviado a ${NOTIFY} \u2014 ${nombre} (${correo})`);
      res.json({ ok: true });
    } catch (err) {
      console.error("\u274C Error enviando email:", err);
      res.status(500).json({ error: "No se pudo enviar el correo. Intente de nuevo." });
    }
  });
  app.post("/api/lead", async (req, res) => {
    const { email, profesion, mascota, departamento, eps, edad, genero, producto } = req.body;
    const html = `
      <div style="font-family:Arial,sans-serif;max-width:600px;margin:0 auto">
        <div style="background:#0B1D34;padding:24px;border-radius:12px 12px 0 0">
          <h2 style="color:#00C5D4;margin:0">\u{1F514} Nuevo c\xE1lculo de tarifa</h2>
          <p style="color:#fff;margin:4px 0 0;font-size:14px">Un usuario us\xF3 el comparador EvaCare</p>
          ${producto ? `<p style="color:#00C5D4;margin:4px 0 0;font-size:13px;font-weight:bold">Producto: ${producto}</p>` : ""}
        </div>
        <div style="border:1px solid #eee;border-top:none;padding:24px;border-radius:0 0 12px 12px">
          <table style="width:100%;border-collapse:collapse">
            ${producto ? `<tr style="background:#E0F7FA"><td style="padding:8px 0;color:#00838F;font-size:14px;width:160px;font-weight:bold">Producto cotizado</td><td style="padding:8px 0;font-weight:700;color:#00838F">${producto}</td></tr>` : ""}
            <tr><td style="padding:8px 0;color:#666;font-size:14px;width:160px">Correo</td><td style="padding:8px 0;font-weight:600">${email}</td></tr>
            ${profesion ? `<tr style="background:#f9f9f9"><td style="padding:8px 0;color:#666;font-size:14px">Profesi\xF3n</td><td style="padding:8px 0;font-weight:600">${profesion}</td></tr>` : ""}
            ${mascota ? `<tr><td style="padding:8px 0;color:#666;font-size:14px">\xBFTiene mascota?</td><td style="padding:8px 0;font-weight:600">${mascota}</td></tr>` : ""}
            ${departamento ? `<tr style="background:#f9f9f9"><td style="padding:8px 0;color:#666;font-size:14px">Departamento</td><td style="padding:8px 0;font-weight:600">${departamento}</td></tr>` : ""}
            ${eps ? `<tr><td style="padding:8px 0;color:#666;font-size:14px">EPS</td><td style="padding:8px 0;font-weight:600">${eps}</td></tr>` : ""}
            ${edad ? `<tr style="background:#f9f9f9"><td style="padding:8px 0;color:#666;font-size:14px">Edad</td><td style="padding:8px 0;font-weight:600">${edad} a\xF1os</td></tr>` : ""}
            ${genero ? `<tr><td style="padding:8px 0;color:#666;font-size:14px">G\xE9nero</td><td style="padding:8px 0;font-weight:600">${genero}</td></tr>` : ""}
          </table>
        </div>
      </div>`;
    try {
      if (process.env.SMTP_USER && process.env.SMTP_PASS) {
        const info = await transporter.sendMail({
          from: `"EvaCare Seguros" <${MAIL_FROM}>`,
          to: NOTIFY,
          replyTo: email,
          subject: `[EvaCare] Nuevo lead${producto ? ` \u2014 ${producto}` : ""} \u2014 ${email}`,
          html
        });
        console.log(`\u2705 [LEAD] enviado a ${NOTIFY} | messageId=${info.messageId} | accepted=${JSON.stringify(info.accepted)} | rejected=${JSON.stringify(info.rejected)} | response=${info.response}`);
      } else {
        console.log("\u{1F4E7} [LEAD sin SMTP]", { email, profesion, mascota, departamento, eps, edad, genero, producto });
      }
      res.json({ ok: true });
    } catch (err) {
      console.error("\u274C [LEAD] error al enviar correo:", err.message);
      res.json({ ok: true });
    }
  });
  app.get("/api/test-email", async (_req, res) => {
    if (!process.env.SMTP_USER || !process.env.SMTP_PASS) {
      res.status(503).json({ ok: false, error: "SMTP no configurado. Configura SMTP_USER y SMTP_PASS en .env" });
      return;
    }
    try {
      await transporter.sendMail({
        from: `"EvaCare Seguros" <${MAIL_FROM}>`,
        to: NOTIFY,
        subject: "\u2705 [EvaCare] Prueba de verificaci\xF3n de correo",
        html: `
          <div style="font-family:Arial,sans-serif;max-width:600px;margin:0 auto">
            <div style="background:#0B1D34;padding:24px;border-radius:12px 12px 0 0">
              <h2 style="color:#00C5D4;margin:0">\u2705 Prueba de verificaci\xF3n</h2>
            </div>
            <div style="border:1px solid #eee;border-top:none;padding:24px;border-radius:0 0 12px 12px">
              <p style="font-size:15px;color:#333">Este es un correo de prueba enviado desde <strong>EvaCare Seguros</strong>.</p>
              <p style="font-size:14px;color:#666">Si recibes este mensaje, la configuraci\xF3n de correo est\xE1 funcionando correctamente.</p>
              <p style="margin-top:16px;padding:12px;background:#E0F7FA;border-radius:8px;font-size:13px;color:#00838F">
                Destino: <strong>${NOTIFY}</strong><br/>
                Fecha: <strong>${(/* @__PURE__ */ new Date()).toLocaleString("es-CO", { timeZone: "America/Bogota" })}</strong>
              </p>
            </div>
          </div>
        `
      });
      console.log(`\u2705 Email de prueba enviado a ${NOTIFY}`);
      res.json({ ok: true, message: `Correo de prueba enviado a ${NOTIFY}` });
    } catch (err) {
      console.error("\u274C Error en test-email:", err);
      res.status(500).json({ ok: false, error: String(err) });
    }
  });
  app.post("/api/schedule-notification", async (req, res) => {
    const { nombre, correo, telefono, planId, planName, profesion, departamento, eps, edad, genero } = req.body;
    const quien = nombre || correo || "Un visitante del comparador";
    const html = `
      <div style="font-family:Arial,sans-serif;max-width:600px;margin:0 auto">
        <div style="background:#0B1D34;padding:24px;border-radius:12px 12px 0 0">
          <h2 style="color:#00C5D4;margin:0">\u{1F4C5} Nuevo agendamiento</h2>
          <p style="color:#fff;margin:4px 0 0;font-size:14px">Una persona est\xE1 interesada en un plan</p>
        </div>
        <div style="border:1px solid #eee;border-top:none;padding:24px;border-radius:0 0 12px 12px">
          <table style="width:100%;border-collapse:collapse">
            <tr style="background:#E0F7FA"><td style="padding:8px 0;color:#00838F;font-size:14px;font-weight:bold;width:160px">Plan de inter\xE9s</td><td style="padding:8px 0;font-weight:700;color:#00838F">${planName} (ID: ${planId})</td></tr>
            ${nombre ? `<tr><td style="padding:8px 0;color:#666;font-size:14px;font-weight:bold">Nombre</td><td style="padding:8px 0;font-weight:600">${nombre}</td></tr>` : ""}
            ${correo ? `<tr style="background:#f9f9f9"><td style="padding:8px 0;color:#666;font-size:14px;font-weight:bold">Correo</td><td style="padding:8px 0;font-weight:600">${correo}</td></tr>` : ""}
            ${telefono ? `<tr><td style="padding:8px 0;color:#666;font-size:14px;font-weight:bold">Tel\xE9fono</td><td style="padding:8px 0;font-weight:600">${telefono}</td></tr>` : ""}
            ${profesion ? `<tr style="background:#f9f9f9"><td style="padding:8px 0;color:#666;font-size:14px;font-weight:bold">Profesi\xF3n</td><td style="padding:8px 0;font-weight:600">${profesion}</td></tr>` : ""}
            ${departamento ? `<tr><td style="padding:8px 0;color:#666;font-size:14px;font-weight:bold">Departamento</td><td style="padding:8px 0;font-weight:600">${departamento}</td></tr>` : ""}
            ${eps ? `<tr style="background:#f9f9f9"><td style="padding:8px 0;color:#666;font-size:14px;font-weight:bold">EPS</td><td style="padding:8px 0;font-weight:600">${eps}</td></tr>` : ""}
            ${edad ? `<tr><td style="padding:8px 0;color:#666;font-size:14px;font-weight:bold">Edad</td><td style="padding:8px 0;font-weight:600">${edad} a\xF1os</td></tr>` : ""}
            ${genero ? `<tr style="background:#f9f9f9"><td style="padding:8px 0;color:#666;font-size:14px;font-weight:bold">G\xE9nero</td><td style="padding:8px 0;font-weight:600">${genero}</td></tr>` : ""}
            <tr><td style="padding:8px 0;color:#666;font-size:14px;font-weight:bold">Acci\xF3n</td><td style="padding:8px 0;font-weight:600">Procede a Google Calendar para confirmar la cita</td></tr>
          </table>
          <p style="margin-top:16px;padding:12px;background:#FFF3E0;border-radius:8px;font-size:13px;color:#E65100">
            <strong>\u23F0 Pr\xF3ximo paso:</strong> El cliente est\xE1 en Google Calendar agendando su asesor\xEDa. Espera la confirmaci\xF3n del calendario.
          </p>
        </div>
      </div>`;
    try {
      if (process.env.SMTP_USER && process.env.SMTP_PASS) {
        const info = await transporter.sendMail({
          from: `"EvaCare Seguros" <${MAIL_FROM}>`,
          to: NOTIFY,
          ...correo ? { replyTo: correo } : {},
          subject: `[EvaCare] Agendamiento \u2014 ${quien} interesado en ${planName}`,
          html
        });
        console.log(`\u2705 [SCHEDULE] enviado a ${NOTIFY} | plan=${planName} | cliente=${quien} | messageId=${info.messageId}`);
      } else {
        console.log("\u{1F4E7} [SCHEDULE sin SMTP]", { nombre, correo, telefono, planId, planName });
      }
      res.json({ ok: true });
    } catch (err) {
      console.error("\u274C [SCHEDULE] error al enviar correo:", err.message);
      res.json({ ok: true });
    }
  });
  const staticPath = path2.resolve(__dirname2, "public");
  app.use(express.static(staticPath));
  app.get("*", (_req, res) => {
    res.sendFile(path2.join(staticPath, "index.html"));
  });
  const port = process.env.PORT || 3e3;
  server.listen(port, () => {
    console.log(`EvaCare server running on http://localhost:${port}/`);
  });
}
startServer().catch(console.error);
