import { notFound } from "next/navigation";
import { EmployeeDetail } from "@/components/employees/EmployeeDetail";
import { createClient } from "@/lib/supabase/server";

type PageProps = { params: Promise<{ id: string }> };

export default async function EmployeeDetailPage({ params }: PageProps) {
  const { id } = await params;
  const supabase = await createClient();

  const {
    data: { user },
  } = await supabase.auth.getUser();
  const { data: profile } = await supabase.from("profiles").select("role").eq("id", user!.id).single();
  const canEdit = profile?.role === "hr_admin";

  const { data: employee } = await supabase.from("employees_directory").select("*").eq("id", id).single();
  if (!employee) notFound();

  const [{ data: manager }, { data: directReports }, { data: history }, { data: divisions }, { data: departments }, { data: teams }, { data: locations }, { data: openPositions }] =
    await Promise.all([
      employee.manager_id
        ? supabase.from("employees_directory").select("id, first_name, last_name, job_title").eq("id", employee.manager_id).single()
        : Promise.resolve({ data: null }),
      supabase
        .from("employees_directory")
        .select("id, first_name, last_name, job_title, status")
        .eq("manager_id", id)
        .order("last_name"),
      supabase.from("employee_history").select("*").eq("employee_id", id).order("event_date", { ascending: false }).order("created_at", { ascending: false }),
      supabase.from("divisions").select("*").order("name"),
      supabase.from("departments").select("*"),
      supabase.from("teams").select("*"),
      supabase.from("locations").select("*").order("name"),
      supabase.from("positions").select("id, position_number, title, team_id, is_lead").eq("status", "open"),
    ]);

  return (
    <EmployeeDetail
      employee={employee}
      manager={manager ?? null}
      directReports={directReports ?? []}
      history={history ?? []}
      divisions={divisions ?? []}
      departments={departments ?? []}
      teams={teams ?? []}
      locations={locations ?? []}
      openPositions={openPositions ?? []}
      canEdit={canEdit}
    />
  );
}
