import { NextResponse } from 'next/server';
import { withV1ErrorHandler } from '@server/middleware/v1Errors';
import { withApiKey, ApiKeyRequest } from '@server/middleware/withApiKey';
import { withV1Validation } from '@server/middleware/v1Validation';
import { ParsedRequest } from '@server/middleware/withValidation';
import { parseListParams, buildListEnvelope, CursorError, cursorErrorResponse } from '@server/middleware/v1Pagination';
import { createOrderSchema, CreateOrderInput } from '@server/validators/orders.validator';
import { listOrders, createOrder } from '@server/services/orders.service';

export const GET = withV1ErrorHandler(
  withApiKey(async (req: ApiKeyRequest) => {
    const url = new URL(req.url);
    let pager;
    try { pager = parseListParams(url); }
    catch (e) { if (e instanceof CursorError) return cursorErrorResponse(e); throw e; }

    const result = await listOrders({
      restaurantId: req.apiKey.restaurantId,
      branchId: url.searchParams.get('branch_id') ?? undefined,
      customerId: url.searchParams.get('customer_id') ?? undefined,
      status: url.searchParams.get('status') ?? undefined,
      channel: url.searchParams.get('channel') ?? undefined,
      search: url.searchParams.get('search') ?? undefined,
      // Public params are `from`/`to`; the underlying service expects
      // `startDate`/`endDate`. Accept both names so partners can use either.
      startDate: url.searchParams.get('from') ?? url.searchParams.get('start_date') ?? undefined,
      endDate:   url.searchParams.get('to')   ?? url.searchParams.get('end_date')   ?? undefined,
      page: pager.page,
      limit: pager.limit,
      sortField: url.searchParams.get('sort') ?? undefined,
      sortDir: url.searchParams.get('dir') ?? undefined,
    });
    return NextResponse.json(buildListEnvelope(result.data, pager.page, pager.limit));
  }, { permission: 'orders:read' })
);

export const POST = withV1ErrorHandler(
  withApiKey(
    withV1Validation(createOrderSchema, async (req: ParsedRequest<CreateOrderInput>) => {
      const apiReq = req as ParsedRequest<CreateOrderInput> & ApiKeyRequest;
      const order = await createOrder(
        apiReq.apiKey.restaurantId,
        req.parsedBody as unknown as Record<string, unknown>
      );
      return NextResponse.json({ data: order }, { status: 201 });
    }),
    { permission: 'orders:write' }
  )
);
