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

async function getProjects() {
  return db.project.findMany({
    where: { status: { in: ["ACTIVE", "ON_HOLD"] } },
    select: { id: true, name: true, code: true, projectType: true },
    orderBy: { name: "asc" },
  });
}

async function getEpisodeDueDatesForProject(projectId: string) {
  return db.episodeDueDate.findMany({
    where: { projectId },
    select: { episode: true, dueDate: true },
    orderBy: { episode: "asc" },
  });
}

async function getShotsForProject(projectId: string) {
  return db.shot.findMany({
    where: { projectId },
    orderBy: [
      { episode: { sort: "asc", nulls: "last" } },
      { scene: "asc" },
      { shotNumber: "asc" },
    ],
    select: {
      id: true,
      shotCode: true,
      scene: true,
      episode: true,
      shotNumber: true,
      status: true,
      priority: true,
      dueDate: true,
      thumbnailUrl: true,
      notes: true,
      description: true,
      artist: { select: { id: true, name: true, image: true, email: true } },
    },
  });
}

export default async function ShotStatusPage({
  searchParams,
}: {
  searchParams: Promise<{ projectId?: string }>;
}) {
  const session = await auth();
  if (!session?.user) redirect("/login");

  const { projectId } = await searchParams;
  const canManage = ["ADMIN", "PRODUCER", "SUPERVISOR"].includes(session.user.role);

  const [projects, shots, episodeDueDates] = await Promise.all([
    getProjects(),
    projectId ? getShotsForProject(projectId) : Promise.resolve([]),
    projectId ? getEpisodeDueDatesForProject(projectId) : Promise.resolve([]),
  ]);

  const selectedProject = projects.find((p) => p.id === projectId) ?? null;

  return (
    <ShotStatusClient
      projects={projects}
      selectedProjectId={projectId ?? null}
      selectedProject={selectedProject}
      shots={shots as any}
      episodeDueDates={episodeDueDates}
      canManage={canManage}
    />
  );
}
