import { prisma } from "./prisma";

type FormData = Record<string, unknown>;
type RespuestaPayload = {
  key: string;
  value: unknown;
  section_id?: string;
};

const CORE_KEYS = new Set([
  "nombre",
  "segundo_nombre",
  "apellido",
  "documentos",
  "correo",
  "fecha_nacimiento",
  "nacionalidad",
  "sexo",
  "direccion_completa",
  "ciudad",
  "estado",
  "pais",
  "postal",
  "telefono",
  "whatsapp",
  "profesion",
  "lugar_trabajo_actual",
  "nivel_academico",
  "nombre_completo",
  "confirmar_nombre",
  "confirmar_firma",
]);

function isBlank(v: unknown): boolean {
  return v === undefined || v === null || v === "";
}

export async function emailExistsInDb(email: string): Promise<boolean> {
  const normalized = (email || "").trim().toLowerCase();
  if (!normalized) return false;
  const found = await prisma.formulario.findFirst({
    where: { correo: { equals: normalized, mode: "insensitive" } },
    select: { id: true },
  });
  return Boolean(found);
}

export async function saveFormularioToSupabase(
  formData: FormData,
  responses: RespuestaPayload[]
) {
  const core = {
    nombre: (formData.nombre as string) ?? "",
    segundo_nombre: (formData.segundo_nombre as string) || null,
    apellido: (formData.apellido as string) ?? "",
    documento_nro: (formData.documentos as string) || null,
    correo: (formData.correo as string) ?? "",
    fecha_nacimiento: formData.fecha_nacimiento
      ? new Date(formData.fecha_nacimiento as string)
      : null,
    nacionalidad: (formData.nacionalidad as string) || null,
    sexo: (formData.sexo as string) || null,
    direccion: (formData.direccion_completa as string) || null,
    ciudad: (formData.ciudad as string) || null,
    estado: (formData.estado as string) || null,
    pais: (formData.pais as string) || null,
    codigo_postal: (formData.postal as string) || null,
    telefono: (formData.telefono as string) || null,
    whatsapp: (formData.whatsapp as string) || null,
    profesion: (formData.profesion as string) || null,
    lugar_trabajo: (formData.lugar_trabajo_actual as string) || null,
    nivel_academico: (formData.nivel_academico as string) || null,
  };

  const respRows: {
    key: string;
    value: string;
    seccion: string;
  }[] = [];

  for (const r of responses || []) {
    if (CORE_KEYS.has(r.key)) continue;
    if (isBlank(r.value)) continue;

    if (Array.isArray(r.value)) {
      for (const v of r.value) {
        if (!isBlank(v)) {
          respRows.push({
            key: r.key,
            value: String(v),
            seccion: r.section_id ?? "",
          });
        }
      }
    } else {
      respRows.push({
        key: r.key,
        value: String(r.value),
        seccion: r.section_id ?? "",
      });
    }
  }

  return prisma.$transaction(async (tx) => {
    const form = await tx.formulario.create({ data: core });
    if (respRows.length) {
      await tx.respuesta.createMany({
        data: respRows.map((r) => ({ ...r, formulario_id: form.id })),
      });
    }
    return form;
  });
}
