import { auth } from "@/auth";
import { db } from "@/lib/db";
import { redirect } from "next/navigation";
import { SchedulePageClient } from "./SchedulePageClient";

export const metadata = { title: "Schedule" };

export default async function SchedulePage({
  searchParams,
}: {
  searchParams: Promise<{ project?: string; artist?: string; status?: string }>;
}) {
  const session = await auth();
  if (!session?.user) redirect("/login");
  if (session.user.role === "CLIENT") redirect("/dashboard");

  const { project, artist, status } = await searchParams;

  const [artists, scheduledTasks, backlogTasks, projects] = await Promise.all([
    db.user.findMany({
      where: { isActive: true, role: { not: "CLIENT" } },
      select: { id: true, name: true, email: true, image: true, role: true },
      orderBy: [{ role: "asc" }, { name: "asc" }],
    }),

    db.task.findMany({
      where: {
        scheduledStartDate: { not: null },
        status: { not: "DONE" },
        ...(project ? { projectId: project } : {}),
        ...(artist ? { assignedArtistId: artist } : {}),
      },
      include: {
        shot: { select: { id: true, shotCode: true, thumbnailUrl: true } },
        asset: { select: { id: true, assetCode: true, name: true } },
        project: { select: { id: true, name: true, code: true } },
        assignedArtist: {
          select: { id: true, name: true, email: true, image: true },
        },
      },
      orderBy: { scheduledStartDate: "asc" },
    }),

    db.task.findMany({
      where: {
        scheduledStartDate: null,
        status: { not: "DONE" },
        ...(project ? { projectId: project } : {}),
        ...(artist ? { assignedArtistId: artist } : {}),
      },
      include: {
        shot: { select: { id: true, shotCode: true, thumbnailUrl: true } },
        asset: { select: { id: true, assetCode: true, name: true } },
        project: { select: { id: true, name: true, code: true } },
        assignedArtist: {
          select: { id: true, name: true, email: true, image: true },
        },
      },
      orderBy: [{ dueDate: "asc" }, { priority: "desc" }],
    }),

    db.project.findMany({
      where: { status: "ACTIVE" },
      select: { id: true, name: true, code: true },
      orderBy: { name: "asc" },
    }),
  ]);

  const canEdit = ["ADMIN", "PRODUCER", "SUPERVISOR"].includes(
    session.user.role
  );

  const serializeTask = (t: (typeof scheduledTasks)[number]) => ({
    ...t,
    dueDate: t.dueDate ? t.dueDate.toISOString() : null,
    scheduledStartDate: t.scheduledStartDate ? t.scheduledStartDate.toISOString() : null,
    scheduledEndDate: t.scheduledEndDate ? t.scheduledEndDate.toISOString() : null,
  });

  return (
    <SchedulePageClient
      artists={artists}
      tasks={scheduledTasks.map(serializeTask)}
      backlog={backlogTasks.map(serializeTask)}
      projects={projects}
      canEdit={canEdit}
      currentUserId={session.user.id}
      activeProject={project}
      activeArtist={artist}
    />
  );
}
