import { NextRequest, NextResponse } from "next/server";
import { z } from "zod";
import { db, supportTickets, supportTicketAttachments, eq } from "@epicure/db";
import { requireAdmin } from "@/lib/api-auth";
import { createGiteaIssue, buildGiteaIssueBody, setGiteaIssueState } from "@/lib/gitea";

const UpdateTicketBody = z.object({
  status: z.enum(["open", "triaged", "closed"]).optional(),
  retryGitea: z.boolean().optional(),
});

export async function PATCH(req: NextRequest, { params }: { params: Promise<{ id: string }> }) {
  const { response } = await requireAdmin();
  if (response) return response;

  const { id } = await params;
  const body = (await req.json()) as unknown;
  const parsed = UpdateTicketBody.safeParse(body);
  if (!parsed.success) {
    return NextResponse.json({ error: "Validation error", issues: parsed.error.issues }, { status: 400 });
  }

  const [ticket] = await db.select().from(supportTickets).where(eq(supportTickets.id, id));
  if (!ticket) return NextResponse.json({ error: "Not found" }, { status: 404 });

  const updates: Partial<typeof ticket> = { updatedAt: new Date() };

  if (parsed.data.status) {
    updates.status = parsed.data.status;
    // Mirror the status change onto the linked Gitea issue — best-effort,
    // never blocks the ticket update on Gitea being reachable.
    if (ticket.giteaIssueNumber && parsed.data.status !== ticket.status) {
      void setGiteaIssueState(ticket.giteaIssueNumber, parsed.data.status === "closed" ? "closed" : "open");
    }
  }

  if (parsed.data.retryGitea) {
    const attachments = await db
      .select({ key: supportTicketAttachments.storageKey, contentType: supportTicketAttachments.contentType })
      .from(supportTicketAttachments)
      .where(eq(supportTicketAttachments.ticketId, id));

    const { url, number, error } = await createGiteaIssue({
      type: ticket.type,
      title: ticket.title,
      body: buildGiteaIssueBody({ description: ticket.description, userId: ticket.userId, attachments }),
    });
    updates.giteaIssueUrl = url;
    updates.giteaIssueNumber = number;
    updates.giteaError = error;
  }

  await db.update(supportTickets).set(updates).where(eq(supportTickets.id, id));

  return NextResponse.json({ ok: true });
}
