import { notFound, redirect } from "next/navigation";
import Link from "next/link";
import { db } from "@/lib/db";
import { auth } from "@/auth";
import { TaskDetailClient } from "./TaskDetailClient";

export async function generateMetadata({ params }: { params: Promise<{ taskId: string }> }) {
  const { taskId } = await params;
  const task = await db.task.findUnique({ where: { id: taskId }, select: { title: true } });
  return { title: task?.title ?? "Task" };
}

async function getTask(taskId: string) {
  return db.task.findUnique({
    where: { id: taskId },
    include: {
      shot: { select: { id: true, shotCode: true, projectId: true } },
      asset: { select: { id: true, assetCode: true, name: true, projectId: true } },
      assignedArtist: { select: { id: true, name: true, email: true, image: true, role: true } },
      createdBy: { select: { id: true, name: true, email: true } },
      project: { select: { id: true, name: true, code: true } },
      versions: {
        orderBy: { versionNumber: "desc" },
        include: {
          artist: { select: { id: true, name: true, image: true, email: true } },
          _count: { select: { comments: true } },
          approvals: {
            orderBy: { createdAt: "desc" },
            take: 1,
            include: { user: { select: { id: true, name: true, role: true } } },
          },
          comments: {
            orderBy: { createdAt: "asc" },
            include: {
              author: { select: { id: true, name: true, email: true, image: true, role: true } },
              replies: {
                orderBy: { createdAt: "asc" },
                include: {
                  author: { select: { id: true, name: true, email: true, image: true, role: true } },
                },
              },
            },
          },
        },
      },
    },
  });
}

async function getProjectArtists(projectId: string) {
  return db.user.findMany({
    where: {
      isActive: true,
    },
    select: { id: true, name: true, email: true, image: true, role: true },
    orderBy: { name: "asc" },
  });
}

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

  const task = await getTask(taskId);
  if (!task) notFound();

  const artists = await getProjectArtists(task.projectId);

  const canManage = ["ADMIN", "PRODUCER", "SUPERVISOR"].includes(session.user.role);
  const isAssigned = task.assignedArtistId === session.user.id;
  const canUpload = canManage || isAssigned;

  return (
    <TaskDetailClient
      task={task as any}
      artists={artists}
      currentUserId={session.user.id}
      canManage={canManage}
      canUpload={canUpload}
    />
  );
}
