import { NextResponse } from "next/server";
import { cookies } from "next/headers";
import { createRouteHandlerClient } from "@supabase/auth-helpers-nextjs";

export const dynamic = "force-dynamic";

export async function GET(_: Request, { params }: { params: { id: string } }) {
  const sb = createRouteHandlerClient({ cookies });
  const { data, error } = await sb
    .from("tickets")
    .select("id, org_id, subject, status, priority, created_by, assigned_to, source, last_message_at, message_count, unread_by_client, unread_by_staff, created_at, updated_at")
    .eq("id", params.id)
    .maybeSingle();
  if (error) return NextResponse.json({ error: error.message }, { status: 400 });
  if (!data) return new NextResponse("Not Found", { status: 404 });
  return NextResponse.json(data);
}

export async function PATCH(req: Request, { params }: { params: { id: string } }) {
  const sb = createRouteHandlerClient({ cookies });
  const { data: { user } } = await sb.auth.getUser();
  if (!user) return new NextResponse("Unauthorized", { status: 401 });

  const payload = await req.json().catch(() => ({}));
  const allowed: Record<string, any> = {};
  if (payload.status) allowed.status = String(payload.status);
  if (payload.assigned_to === null) allowed.assigned_to = null;
  else if (typeof payload.assigned_to === "string") allowed.assigned_to = payload.assigned_to;

  if (Object.keys(allowed).length === 0) {
    return NextResponse.json({ error: "Aucun champ modifiable fourni" }, { status: 400 });
  }

  const { data, error } = await sb
    .from("tickets")
    .update(allowed)
    .eq("id", params.id)
    .select("*")
    .maybeSingle();
  if (error) return NextResponse.json({ error: error.message }, { status: 400 });
  return NextResponse.json(data);
}

