import { NextResponse } from 'next/server';
import { withErrorHandler, RouteContext } from '@server/middleware/withErrorHandler';
import { withAuth, AuthedRequest } from '@server/middleware/withAuth';
import { withValidationAuthed } from '@server/middleware/withValidation';
import { updateTicketSchema } from '@server/validators/support-tickets.validator';
import { getTicket, updateTicket, appendTicketMessage, deleteTicket } from '@server/services/support-tickets.service';

export const GET = withErrorHandler(
  withAuth(async (req: AuthedRequest, ctx: RouteContext) => {
    const { id } = await ctx.params;
    const ticket = await getTicket(id, req.session.restaurantId!);
    return NextResponse.json({ ticket });
  })
);

export const PATCH = withErrorHandler(
  withAuth(
    withValidationAuthed(updateTicketSchema, async (req, ctx: RouteContext) => {
      const { id } = await ctx.params;
      const body = req.parsedBody;

      if (body.messages && body.messages.length > 0) {
        const msg = body.messages[0];
        const ticket = await appendTicketMessage(id, req.session.restaurantId!, {
          role: msg.is_staff ? 'assistant' : 'user',
          content: msg.content,
        });
        return NextResponse.json({ ticket });
      }

      const ticket = await updateTicket(id, req.session.restaurantId!, body as Record<string, unknown>);
      return NextResponse.json({ ticket });
    })
  )
);

export const DELETE = withErrorHandler(
  withAuth(async (req: AuthedRequest, ctx: RouteContext) => {
    const { id } = await ctx.params;
    await deleteTicket(id, req.session.restaurantId!);
    return NextResponse.json({ success: true });
  })
);
