"use server";
import { db } from '@/lib/db';
import { colegio, user, curso, noticia, clase, chatconversacion, mensajecontacto } from '@/db/schema';
import { eq, count } from 'drizzle-orm';
import { revalidatePath } from "next/cache";
import { getServerSession } from "next-auth";
import { authOptions } from "@/lib/auth";
import bcrypt from "bcryptjs";
import crypto from "crypto";

async function checkSuperAdmin() {
  const session = await getServerSession(authOptions);
  if (!session || session.user.role !== "SUPERADMIN") {
    throw new Error("No autorizado. Se requiere SuperAdmin.");
  }
  return session;
}

export async function toggleColegioStatus(id: string, activo: boolean) {
  try {
    await checkSuperAdmin();
    await db.update(colegio)
      .set({ activo, updatedAt: new Date() })
      .where(eq(colegio.id, id));
    revalidatePath("/dashboard/colegios");
    return { success: true };
  } catch (error: any) {
    return { success: false, error: error.message || "No se pudo cambiar el estado del colegio" };
  }
}

export async function createColegio(formData: FormData) {
  try {
    await checkSuperAdmin();
    const nombre    = formData.get("nombre") as string;
    const ubicacion = (formData.get("ubicacion") as string) || null;
    const whatsapp  = (formData.get("whatsapp") as string) || null;
    const email     = (formData.get("email") as string) || null;
    const telefono  = (formData.get("telefono") as string) || null;
    const logoUrl   = (formData.get("logoUrl") as string) || null;
    const color     = (formData.get("color") as string) || "#1e2a47";
    const requisitosInscripcion = (formData.get("requisitosInscripcion") as string) || null;
    
    const adminPassword = formData.get("adminPassword") as string;

    if (!email) {
      throw new Error("El email es requerido para poder crear el usuario administrador de la sede.");
    }
    if (!adminPassword) {
      throw new Error("La contraseña del administrador es requerida.");
    }

    // Verificar si el email ya existe
    const existingUser = await db.query.user.findFirst({
      where: eq(user.email, email)
    });
    if (existingUser) {
      throw new Error("Ya existe un usuario con este email en el sistema.");
    }

    const hashedPassword = await bcrypt.hash(adminPassword, 10);

    // Transacción: Crear colegio y usuario administrador al mismo tiempo
    await db.transaction(async (tx) => {
      const colegioId = crypto.randomUUID();
      await tx.insert(colegio).values({
        id: colegioId,
        nombre,
        ubicacion,
        whatsapp,
        email,
        telefono,
        logoUrl,
        color,
        requisitosInscripcion,
        activo: true,
        updatedAt: new Date()
      });

      await tx.insert(user).values({
        id: crypto.randomUUID(),
        email,
        name: `Director ${nombre}`,
        password: hashedPassword,
        role: "ADMIN_COLEGIO",
        colegioId: colegioId,
        status: "SOLVENTE",
        updatedAt: new Date()
      });
    });

    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 superAdmins = await db.query.user.findMany({
        where: eq(user.role, "SUPERADMIN"),
        columns: { email: true }
      });
      const recipients = new Set<string>();
      if (email) recipients.add(email);
      superAdmins.forEach(admin => {
        if (admin.email) recipients.add(admin.email);
      });

      if (recipients.size > 0) {
        const mailOptions = {
          from: `"Cursos Nirgua" <info@cursos.nirgua.com.ve>`,
          to: Array.from(recipients).join(", "),
          subject: `Registro de Sede / Colegio: ${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;">Nueva Institución Registrada</h2>
              <p>Se ha registrado la institución <strong>${nombre}</strong> en Cursos Nirgua.</p>
              <hr style="border: 0; border-top: 1px solid #eee;" />
              <p>Credenciales de acceso para el administrador de la sede:</p>
              <p><strong>URL de Acceso:</strong> <a href="https://cursos.nirgua.com.ve/signin">https://cursos.nirgua.com.ve/signin</a></p>
              <p><strong>Usuario / Correo:</strong> ${email}</p>
              <p><strong>Contraseña:</strong> ${adminPassword}</p>
            </div>
          `,
        };
        await transporter.sendMail(mailOptions);
      }
    } catch (mailError) {
      console.error("Error enviando correo de colegio:", mailError);
    }

    revalidatePath("/dashboard/colegios");
    return { success: true };
  } catch (error: any) {
    return { success: false, error: error.message || "Error al crear colegio" };
  }
}

export async function updateColegio(id: string, formData: FormData) {
  try {
    const session = await getServerSession(authOptions);
    if (!session || (session.user.role !== "SUPERADMIN" && (session.user.role !== "ADMIN_COLEGIO" || session.user.colegioId !== id))) {
      return { success: false, error: "No autorizado para modificar esta sede." };
    }

    const nombre    = formData.get("nombre") as string;
    const ubicacion = (formData.get("ubicacion") as string) || null;
    const whatsapp  = (formData.get("whatsapp") as string) || null;
    const email     = (formData.get("email") as string) || null;
    const telefono  = (formData.get("telefono") as string) || null;
    const logoUrl   = (formData.get("logoUrl") as string) || null;
    const color     = (formData.get("color") as string) || "#1e2a47";
    const requisitosInscripcion = (formData.get("requisitosInscripcion") as string) || null;

    await db.update(colegio)
      .set({
        nombre,
        ubicacion,
        whatsapp,
        email,
        telefono,
        logoUrl,
        color,
        requisitosInscripcion,
        updatedAt: new Date()
      })
      .where(eq(colegio.id, id));

    revalidatePath("/dashboard/colegios");
    revalidatePath("/(full-width-pages)/sedes");
    return { success: true };
  } catch (error) {
    return { success: false, error: "Error al actualizar la sede." };
  }
}

export async function deleteColegio(id: string) {
  try {
    await checkSuperAdmin();

    // Verificamos si tiene registros asociados
    const [
      [userRes],
      [cursoRes],
      [noticiaRes],
      [claseRes],
      [chatRes],
      [contactRes]
    ] = await Promise.all([
      db.select({ value: count() }).from(user).where(eq(user.colegioId, id)),
      db.select({ value: count() }).from(curso).where(eq(curso.colegioId, id)),
      db.select({ value: count() }).from(noticia).where(eq(noticia.colegioId, id)),
      db.select({ value: count() }).from(clase).where(eq(clase.colegioId, id)),
      db.select({ value: count() }).from(chatconversacion).where(eq(chatconversacion.colegioId, id)),
      db.select({ value: count() }).from(mensajecontacto).where(eq(mensajecontacto.colegioId, id)),
    ]);

    const totalRecords = userRes.value + cursoRes.value + noticiaRes.value + claseRes.value + chatRes.value + contactRes.value;

    if (totalRecords > 0) {
      throw new Error("Tiene registros asociados, no se puede borrar. Borre primero los registros para eliminar el colegio.");
    }

    await db.delete(colegio)
      .where(eq(colegio.id, id));

    revalidatePath("/dashboard/colegios");
    return { success: true };
  } catch (error: any) {
    return { success: false, error: error.message || "Error al eliminar la sede permanentemente." };
  }
}
