import { NextResponse } from 'next/server';
import { withErrorHandler } from '@server/middleware/withErrorHandler';
import { withAuth, AuthedRequest } from '@server/middleware/withAuth';
import { withValidationAuthed } from '@server/middleware/withValidation';
import { createTicketSchema } from '@server/validators/support-tickets.validator';
import { listTickets, createTicket } from '@server/services/support-tickets.service';

export const GET = withErrorHandler(
  withAuth(async (req: AuthedRequest) => {
    const { restaurantId } = req.session;
    const url = new URL(req.url);
    const p = url.searchParams;

    const result = await listTickets({
      restaurantId: restaurantId!,
      status: p.get('status') ?? undefined,
      priority: p.get('priority') ?? undefined,
      search: p.get('search') ?? undefined,
      page: parseInt(p.get('page') ?? '1', 10),
      limit: parseInt(p.get('limit') ?? '20', 10),
    });

    return NextResponse.json({ tickets: result.data, total: result.total, page: result.page, limit: result.limit, pages: result.pages });
  })
);

export const POST = withErrorHandler(
  withAuth(
    withValidationAuthed(createTicketSchema, async (req) => {
      const ticket = await createTicket(
        req.session.restaurantId!,
        req.session.userId,
        req.parsedBody as Record<string, unknown>
      );
      return NextResponse.json({ ticket }, { status: 201 });
    })
  )
);
