import { db } from "@/lib/db";
import { chatconversacion } from "@/db/schema";
import { eq, and } from "drizzle-orm";
import { getServerSession } from "next-auth";
import { authOptions } from "@/lib/auth";
import ChatClient from "./ChatClient";
import { redirect } from "next/navigation";
import { getChatConversaciones } from "@/lib/mariadb-relations";

export const dynamic = "force-dynamic";

export default async function ChatPage() {
  const session = await getServerSession(authOptions);
  if (!session?.user) redirect("/signin");

  const { role, id: userId, colegioId } = session.user;

  if (role === "PROFESOR" && colegioId) {
    const existing = await db.query.chatconversacion.findFirst({
      where: and(
        eq(chatconversacion.profesorId, userId),
        eq(chatconversacion.colegioId, colegioId as string)
      ),
    });
    if (!existing) {
      const crypto = await import("crypto");
      await db.insert(chatconversacion).values({
        id: crypto.randomUUID(),
        profesorId: userId,
        colegioId: colegioId as string,
        updatedAt: new Date(),
      });
    }
  }

  let conversaciones: Awaited<ReturnType<typeof getChatConversaciones>> = [];

  if (role === "PROFESOR") {
    conversaciones = await getChatConversaciones(eq(chatconversacion.profesorId, userId));
  } else if (role === "ADMIN_COLEGIO" && colegioId) {
    conversaciones = await getChatConversaciones(eq(chatconversacion.colegioId, colegioId as string));
  } else if (role === "SUPERADMIN") {
    conversaciones = await getChatConversaciones();
  }

  conversaciones.sort((a, b) => new Date(b.updatedAt).getTime() - new Date(a.updatedAt).getTime());

  const conversacionesAdaptadas = conversaciones.map((conv) => ({
    ...conv,
    profesor: conv.user,
    mensajes: conv.chatmensaje?.map((m) => ({ ...m, sender: m.user })) || [],
  }));

  return (
    <div className="p-8 max-w-7xl mx-auto h-[calc(100vh-100px)] flex flex-col">
      <div className="mb-6">
        <h1 className="text-3xl font-extrabold text-gray-800">Mensajería Interna</h1>
        <p className="text-gray-500">Comunicación entre profesores y administración.</p>
      </div>

      <div className="flex-1 bg-white rounded-2xl shadow-sm border border-gray-100 overflow-hidden flex min-h-0">
        <ChatClient conversaciones={conversacionesAdaptadas} currentUser={session.user} />
      </div>
    </div>
  );
}
