import { NextResponse } from "next/server";
import { DepartmentKey } from "@prisma/client";
import { getServerSession } from "next-auth";
import { authOptions } from "@/lib/auth";
import { prisma } from "@/lib/prisma";
import { canAccessProjects, mapProjectEmployee, mapProjectInitiative, mapProjectTask } from "@/lib/projects/persistence";

export async function GET() {
  const session = await getServerSession(authOptions);
  if (!session?.user) {
    return NextResponse.json({ error: "Unauthorized" }, { status: 401 });
  }

  if (!canAccessProjects(session.user.role, session.user.department)) {
    return NextResponse.json({ error: "Forbidden" }, { status: 403 });
  }

  const [employeesRaw, initiativesRaw] = await Promise.all([
    prisma.user.findMany({
      where: {
        department: DepartmentKey.proyectos,
        status: "active",
      },
      select: {
        id: true,
        name: true,
        email: true,
        departmentRole: true,
        userRoles: {
          include: { role: true },
          orderBy: { assignedAt: "asc" },
          take: 1,
        },
      },
      orderBy: [{ name: "asc" }, { email: "asc" }],
    }),
    prisma.marketingInitiative.findMany({
      where: {
        department: DepartmentKey.proyectos,
        projectsSchemaVersion: 2,
      },
      include: {
        contributors: true,
        locations: true,
        evidenceLinks: {
          orderBy: { createdAt: "asc" },
        },
        tasks: {
          include: {
            evidenceLinks: {
              orderBy: { createdAt: "asc" },
            },
          },
          orderBy: [{ dueDate: "asc" }, { createdAt: "asc" }],
        },
        milestones: {
          include: {
            checkpoints: {
              orderBy: { createdAt: "asc" },
            },
          },
          orderBy: [{ sortOrder: "asc" }, { dueDate: "asc" }],
        },
      },
      orderBy: [{ dueDate: "asc" }, { createdAt: "desc" }],
    }),
  ]);

  const employees = employeesRaw.map(mapProjectEmployee);
  const initiatives = initiativesRaw.map(mapProjectInitiative);
  const tasks = initiativesRaw.flatMap((initiative) =>
    initiative.tasks.map((task) =>
      mapProjectTask({
        ...task,
        initiativeId: initiative.id,
      })
    )
  );

  return NextResponse.json({
    ok: true,
    employees,
    initiatives,
    tasks,
  });
}
