import { NextResponse } from "next/server";
import { db } from "@/lib/db";
import { notificacion, user, curso, chatmensaje, chatconversacion } from "@/db/schema";
import { eq, and, desc, ne, count } from "drizzle-orm";
import { getServerSession } from "next-auth";
import { authOptions } from "@/lib/auth";

export const dynamic = "force-dynamic";

// Crear alias para el segundo join de usuario
const user2 = user;

export async function GET() {
  try {
    const session = await getServerSession(authOptions);
    if (!session?.user) {
      return NextResponse.json({ notificaciones: [] });
    }

    const role = session.user.role;
    const colegioId = session.user.colegioId;
    const userId = session.user.id;

    // Construir condiciones para notificaciones
    const notifConditions = [];
    
    if (role === "ADMIN_COLEGIO" && colegioId) {
      notifConditions.push(eq(notificacion.colegioId, colegioId));
    } else if (role === "PROFESOR") {
      notifConditions.push(eq(notificacion.userId, userId));
    }

    // Construir condiciones para mensajes de chat
    const chatConditions = [eq(chatmensaje.read, false), ne(chatmensaje.senderId, userId)];

    if (role === "ADMIN_COLEGIO" && colegioId) {
      chatConditions.push(eq(chatconversacion.colegioId, colegioId));
      chatConditions.push(ne(chatmensaje.senderId, "ADMIN"));
    } else if (role === "PROFESOR") {
      chatConditions.push(eq(chatconversacion.profesorId, userId));
    } else if (role === "SUPERADMIN") {
      chatConditions.push(ne(chatmensaje.senderId, "ADMIN"));
    }

    // Consultar notificaciones con joins
    const notificacionesQuery = db
      .select({
        id: notificacion.id,
        titulo: notificacion.titulo,
        mensaje: notificacion.mensaje,
        leido: notificacion.leido,
        createdAt: notificacion.createdAt,
        userId: notificacion.userId,
        cursoId: notificacion.cursoId,
        colegioId: notificacion.colegioId,
        userName: user.name,
        cursoTitulo: curso.titulo
      })
      .from(notificacion)
      .leftJoin(user, eq(notificacion.userId, user.id))
      .leftJoin(curso, eq(notificacion.cursoId, curso.id))
      .where(notifConditions.length > 0 ? and(...notifConditions) : undefined)
      .orderBy(desc(notificacion.createdAt))
      .limit(10);

    // Consultar mensajes de chat con joins
    const unreadChatsQuery = db
      .select({
        id: chatmensaje.id,
        contenido: chatmensaje.contenido,
        read: chatmensaje.read,
        createdAt: chatmensaje.createdAt,
        senderId: chatmensaje.senderId,
        conversacionId: chatmensaje.conversacionId,
        senderName: user.name,
        profesorName: user2.name
      })
      .from(chatmensaje)
      .innerJoin(chatconversacion, eq(chatmensaje.conversacionId, chatconversacion.id))
      .innerJoin(user, eq(chatmensaje.senderId, user.id))
      .leftJoin(user as typeof user2, eq(chatconversacion.profesorId, user2.id))
      .where(and(...chatConditions))
      .orderBy(desc(chatmensaje.createdAt))
      .limit(10);

    // Contar notificaciones sin leer
    const sinLeerNotifQuery = db
      .select({ count: count() })
      .from(notificacion)
      .where(and(
        ...notifConditions,
        eq(notificacion.leido, false)
      ));

    // Contar chats sin leer
    const sinLeerChatsQuery = db
      .select({ count: count() })
      .from(chatmensaje)
      .innerJoin(chatconversacion, eq(chatmensaje.conversacionId, chatconversacion.id))
      .where(and(...chatConditions));

    // Ejecutar todas las consultas en paralelo
    const [notificaciones, unreadChats, sinLeerNotifResult, sinLeerChatsResult] = await Promise.all([
      notificacionesQuery,
      unreadChatsQuery,
      sinLeerNotifQuery,
      sinLeerChatsQuery
    ]);

    // Formatear notificaciones
    const formattedNotificaciones = notificaciones.map(n => ({
      id: n.id,
      titulo: n.titulo,
      mensaje: n.mensaje,
      leido: n.leido,
      createdAt: n.createdAt,
      user: n.userName ? { name: n.userName } : null,
      curso: n.cursoTitulo ? { titulo: n.cursoTitulo } : null
    }));

    // Formatear chats
    const formattedChats = (unreadChats as any[]).map((m) => ({
      id: m.id,
      titulo: role === "PROFESOR" ? "Mensaje de la Administración" : `Mensaje de ${m.senderName || m.profesorName || "Instructor"}`,
      mensaje: m.contenido,
      leido: m.read,
      createdAt: m.createdAt,
      type: "CHAT"
    }));

    const sinLeerNotif = sinLeerNotifResult[0]?.count || 0;
    const sinLeerChats = sinLeerChatsResult[0]?.count || 0;

    // Merge and sort them
    const allNotifs = [...formattedNotificaciones, ...formattedChats].sort((a: any, b: any) => 
      new Date(b.createdAt).getTime() - new Date(a.createdAt).getTime()
    ).slice(0, 10);

    return NextResponse.json({ 
      notificaciones: allNotifs, 
      sinLeer: sinLeerNotif + sinLeerChats 
    });
  } catch (error) {
    console.error("Error en API notificaciones:", error);
    return NextResponse.json({ notificaciones: [], sinLeer: 0 });
  }
}
