import { NextRequest, NextResponse } from "next/server";
import crypto from "node:crypto";
import { z } from "zod";
import { db, supportTickets, supportTicketComments, eq, asc } from "@epicure/db";
import { requireSession } from "@/lib/api-auth";
import { postGiteaComment } from "@/lib/gitea";

const CreateCommentBody = z.object({
  body: z.string().trim().min(1).max(3000),
});

export async function GET(_req: NextRequest, { params }: { params: Promise<{ id: string }> }) {
  const { session, response } = await requireSession();
  if (response) return response;

  const { id } = await params;
  const ticket = await db.query.supportTickets.findFirst({ where: eq(supportTickets.id, id) });
  if (!ticket || ticket.userId !== session!.user.id) {
    return NextResponse.json({ error: "Not found" }, { status: 404 });
  }

  const comments = await db.query.supportTicketComments.findMany({
    where: eq(supportTicketComments.ticketId, id),
    orderBy: asc(supportTicketComments.createdAt),
  });

  return NextResponse.json(comments);
}

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

  const { id } = await params;
  const ticket = await db.query.supportTickets.findFirst({ where: eq(supportTickets.id, id) });
  if (!ticket || ticket.userId !== session!.user.id) {
    return NextResponse.json({ error: "Not found" }, { status: 404 });
  }

  const parsed = CreateCommentBody.safeParse(await req.json());
  if (!parsed.success) {
    return NextResponse.json({ error: "Validation error", issues: parsed.error.issues }, { status: 400 });
  }

  let giteaCommentId: number | null = null;
  if (ticket.giteaIssueNumber) {
    const { id: commentId } = await postGiteaComment(ticket.giteaIssueNumber, parsed.data.body);
    giteaCommentId = commentId;
  }

  const commentId = crypto.randomUUID();
  const now = new Date();
  await db.insert(supportTicketComments).values({
    id: commentId,
    ticketId: id,
    authorType: "user",
    authorId: session!.user.id,
    body: parsed.data.body,
    giteaCommentId,
    createdAt: now,
  });

  return NextResponse.json(
    { id: commentId, ticketId: id, authorType: "user", authorId: session!.user.id, body: parsed.data.body, createdAt: now.toISOString() },
    { status: 201 }
  );
}
