"use server";

import { db } from '@/lib/db';
import { user, mensajecontacto, colegio } from '@/db/schema';
import { eq } from 'drizzle-orm';
import { revalidatePath } from "next/cache";
import bcrypt from "bcryptjs";
import crypto from "crypto";

export async function checkEmail(email: string) {
  if (!email) return false;
  const foundUser = await db.query.user.findFirst({
    where: eq(user.email, email),
    columns: { id: true }
  });
  return !!foundUser;
}

export async function submitContact(formData: FormData) {
  const nombre = formData.get("nombre") as string;
  const email = formData.get("email") as string;
  const telefono = (formData.get("telefono") as string) || null;
  const mensaje = formData.get("mensaje") as string;
  const tipo = (formData.get("tipo") as string) || "GENERAL";
  const colegioId = (formData.get("colegioId") as string) || null;

  if (!nombre || !email || !mensaje) {
    return { success: false, error: "Faltan campos obligatorios." };
  }

  try {
    // Verificar si el usuario ya existe
    const existingUser = await db.query.user.findFirst({
      where: eq(user.email, email)
    });
    
    let plainPassword = "";
    const generatedRandomPass = Math.random().toString(36).slice(-8);

    if (existingUser) {
      // Si existe, generar una clave nueva aleatoria de 8 caracteres
      plainPassword = generatedRandomPass;
      const hashedPassword = await bcrypt.hash(plainPassword, 10);
      await db.update(user)
        .set({ password: hashedPassword, updatedAt: new Date() })
        .where(eq(user.id, existingUser.id));
    } else {
      // Si no existe, crear el usuario con la contraseña proporcionada o generada
      plainPassword = (formData.get("password") as string) || generatedRandomPass;
      const hashedPassword = await bcrypt.hash(plainPassword, 10);
      
      let role: "SUPERADMIN" | "ADMIN_COLEGIO" | "PROFESOR" | "ESTUDIANTE" = "ESTUDIANTE";
      let status: "SOLVENTE" | "MOROSO" | "PENDIENTE" = "SOLVENTE";

      if (tipo === "PROFESOR") {
        role = "PROFESOR";
      } else if (tipo === "COLEGIO") {
        role = "ADMIN_COLEGIO";
        status = "PENDIENTE";
      }
      
      await db.insert(user).values({
        id: crypto.randomUUID(),
        name: nombre,
        email,
        password: hashedPassword,
        telefono,
        role,
        status,
        colegioId: colegioId || null,
        updatedAt: new Date()
      });
    }

    const mensajeDb = tipo === "COLEGIO" ? `[SOLICITUD_COLEGIO]\n${mensaje}` : mensaje;

    // Crear registro en base de datos para el mensaje de contacto
    await db.insert(mensajecontacto).values({
      id: crypto.randomUUID(),
      nombre,
      email,
      telefono,
      mensaje: mensajeDb,
      colegioId,
    });

    // Enviar correos con nodemailer
    try {
      const nodemailer = require("nodemailer");
      const transporter = nodemailer.createTransport({
        host: process.env.SMTP_HOST || "localhost",
        port: Number(process.env.SMTP_PORT) || 25,
        secure: process.env.SMTP_SECURE === "true",
        auth: process.env.SMTP_USER ? {
          user: process.env.SMTP_USER,
          pass: process.env.SMTP_PASS,
        } : undefined,
        tls: { rejectUnauthorized: false }
      });

      // --- CORREO PARA EL USUARIO QUE SE REGISTRA ---
      const userMailOptions = {
        from: `"Cursos Nirgua" <info@cursos.nirgua.com.ve>`,
        to: email,
        subject: existingUser 
          ? `Actualización de Clave - Cursos Nirgua` 
          : tipo === "COLEGIO" 
            ? `Solicitud de Registro Recibida - Cursos Nirgua`
            : `Bienvenido a Cursos Nirgua - Tus Credenciales`,
        html: `
          <div style="font-family: sans-serif; color: #333; max-width: 600px; border: 1px solid #eee; padding: 20px; border-radius: 10px;">
            <h2 style="color: #43a047;">${existingUser ? "Nueva clave de acceso" : tipo === "COLEGIO" ? "Solicitud en Revisión" : "¡Registro Exitoso!"}</h2>
            <p>Hola <strong>${nombre}</strong>,</p>
            <p>${existingUser 
              ? "Hemos generado una nueva clave aleatoria de 8 caracteres para tu cuenta." 
              : tipo === "COLEGIO"
              ? "Tu registro de institución está en proceso de revisión y debe ser aprobado por la administración. Una vez aprobado, te notificaremos por este medio."
              : "Tu registro en la plataforma se ha realizado con éxito."}</p>
            <p><strong>Usuario (Correo):</strong> ${email}</p>
            <p><strong>Contraseña:</strong> ${plainPassword}</p>
            <br/>
            <p>Por favor, guarda esta información en un lugar seguro.</p>
            <p style="font-size: 12px; color: #999; margin-top: 20px;">
              Este es un correo automático generado por el sistema de Cursos Nirgua.
            </p>
          </div>
        `,
      };
      await transporter.sendMail(userMailOptions);

      // --- CORREO DE NOTIFICACIÓN A ADMINISTRADORES ---
      let adminRecipients = ["info@cursos.nirgua.com.ve", "bauste98@gmail.com"];
      
      if ((tipo === "PROFESOR" || tipo === "ESTUDIANTE") && colegioId) {
        const foundColegio = await db.query.colegio.findFirst({
          where: eq(colegio.id, colegioId),
          columns: { email: true, nombre: true }
        });
        if (foundColegio?.email) {
          adminRecipients.push(foundColegio.email);
        }
      }

      const adminMailOptions = {
        from: `"Cursos Nirgua Notificaciones" <info@cursos.nirgua.com.ve>`,
        to: adminRecipients.join(", "),
        subject: `[${tipo}] Nuevo Registro/Contacto: ${nombre}`,
        html: `
          <div style="font-family: sans-serif; color: #333; max-width: 600px; border: 1px solid #eee; padding: 20px; border-radius: 10px;">
            <h2 style="color: #43a047;">Nuevo registro desde la plataforma</h2>
            <p>Se ha recibido una nueva solicitud de tipo: <strong>${tipo}</strong></p>
            <hr style="border: 0; border-top: 1px solid #eee;" />
            <p><strong>Nombre:</strong> ${nombre}</p>
            <p><strong>Email:</strong> ${email}</p>
            <p><strong>Teléfono:</strong> ${telefono || "N/A"}</p>
            <p><strong>Mensaje:</strong></p>
            <p style="background: #f9f9f9; padding: 15px; border-radius: 5px;">${mensaje}</p>
            <p style="font-size: 12px; color: #999; margin-top: 20px;">
              Este es un correo automático generado por el sistema de Cursos Nirgua.
            </p>
          </div>
        `,
      };
      await transporter.sendMail(adminMailOptions);

    } catch (mailError) {
      console.error("Error enviando los correos:", mailError);
    }

    // Revalidar la vista de notificaciones del admin
    revalidatePath("/dashboard/usuarios");
    revalidatePath("/dashboard/notificaciones");

    return { success: true };
  } catch (error) {
    console.error("Error al procesar registro:", error);
    return { success: false, error: "Error interno del servidor." };
  }
}
