export const dynamic = "force-dynamic";
import { cookies } from "next/headers";
import { createSbServer } from "@/lib/supabaseServer";
import NewStaffTicketForm from "@/components/staff/NewStaffTicketForm";
import { Metadata } from "next";

export const metadata: Metadata = {
  title: "Nouveau ticket | Espace Paie Odentas",
};

export default async function StaffNewTicketPage() {
  const sb = createSbServer();
  const { data: { user } } = await sb.auth.getUser();
  if (!user) return (<main className="p-6"><h1 className="text-lg font-semibold">Accès refusé</h1></main>);

  const { data: me } = await sb
    .from("staff_users")
    .select("is_staff")
    .eq("user_id", user.id)
    .maybeSingle();
  if (!me?.is_staff) return (<main className="p-6"><h1 className="text-lg font-semibold">Accès refusé</h1></main>);

  const c = cookies();
  const activeOrgId = c.get("active_org_id")?.value || "";
  const { data: orgs } = await sb.from("organizations").select("id, name").order("name", { ascending: true }).limit(200);

  return (
    <main className="p-6 space-y-4">
      <h1 className="text-lg font-semibold">Nouveau ticket (staff)</h1>
      <NewStaffTicketForm orgs={(orgs || []) as any} activeOrgId={activeOrgId} />
    </main>
  );
}
