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

export async function marcarLeido(id: string) {
  try {
    await db.update(mensajecontacto)
      .set({ leido: true })
      .where(eq(mensajecontacto.id, id));
    revalidatePath("/dashboard/notificaciones");
    return { success: true };
  } catch {
    return { success: false };
  }
}

export async function eliminarMensaje(id: string) {
  try {
    await db.delete(mensajecontacto)
      .where(eq(mensajecontacto.id, id));
    revalidatePath("/dashboard/notificaciones");
    return { success: true };
  } catch {
    return { success: false };
  }
}

export async function guardarMensajeContacto(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;

  try {
    await db.insert(mensajecontacto).values({
      id: crypto.randomUUID(),
      nombre,
      email,
      telefono,
      mensaje
    });
    return { success: true };
  } catch {
    return { success: false, error: "No se pudo guardar el mensaje." };
  }
}

export async function aprobarInstitucion(mensajeId: string) {
  try {
    const mensaje = await db.query.mensajecontacto.findFirst({
      where: eq(mensajecontacto.id, mensajeId)
    });

    if (!mensaje) return { success: false, error: "Mensaje no encontrado" };

    const foundUser = await db.query.user.findFirst({
      where: eq(user.email, mensaje.email)
    });

    if (!foundUser) return { success: false, error: "Usuario no encontrado" };
    if (foundUser.role !== "ADMIN_COLEGIO") return { success: false, error: "El usuario no es un administrador de colegio" };

    let colegioId = foundUser.colegioId;

    // Si el usuario no tiene colegio asignado, creamos uno nuevo
    if (!colegioId) {
      const nuevoId = crypto.randomUUID();
      await db.insert(colegio).values({
        id: nuevoId,
        nombre: mensaje.nombre,
        email: mensaje.email,
        telefono: mensaje.telefono,
        activo: true,
        updatedAt: new Date()
      });
      colegioId = nuevoId;
    }

    // Actualizar usuario: solvente y asignado al colegio
    await db.update(user)
      .set({
        status: "SOLVENTE",
        colegioId: colegioId,
        updatedAt: new Date()
      })
      .where(eq(user.id, foundUser.id));

    // Enviar correo de aprobación
    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 }
      });

      const mailOptions = {
        from: `"Cursos Nirgua" <info@cursos.nirgua.com.ve>`,
        to: foundUser.email,
        subject: `Institución Aprobada - Cursos Nirgua`,
        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;">¡Felicidades!</h2>
            <p>Hola <strong>${mensaje.nombre}</strong>,</p>
            <p>Tu solicitud de registro como Institución/Colegio ha sido <strong>aprobada</strong> por la administración.</p>
            <p>Ya puedes acceder a la plataforma utilizando tu correo electrónico y la contraseña que recibiste en el momento de tu registro.</p>
            <br/>
            <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(mailOptions);
    } catch (e) {
      console.error("Error enviando correo de aprobación:", e);
    }

    // Limpiamos el prefijo [SOLICITUD_COLEGIO] del mensaje para que ya no muestre el botón
    const nuevoTextoMensaje = mensaje.mensaje.replace("[SOLICITUD_COLEGIO]", "[INSTITUCIÓN APROBADA]");
    await db.update(mensajecontacto)
      .set({ mensaje: nuevoTextoMensaje })
      .where(eq(mensajecontacto.id, mensajeId));

    revalidatePath("/dashboard/notificaciones");
    return { success: true };
  } catch (error) {
    console.error(error);
    return { success: false, error: "Error al aprobar institución" };
  }
}
