import { NextResponse } from 'next/server';
import { withV1ErrorHandler } from '@server/middleware/v1Errors';
import { withApiKey, ApiKeyRequest } from '@server/middleware/withApiKey';
import { parseListParams, buildListEnvelope, CursorError, cursorErrorResponse } from '@server/middleware/v1Pagination';
import { listCustomers } from '@server/services/customers.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 listCustomers({
      restaurantId: req.apiKey.restaurantId,
      branchId: url.searchParams.get('branch_id') ?? undefined,
      search: url.searchParams.get('search') ?? undefined,
      page: pager.page,
      limit: pager.limit,
    });
    return NextResponse.json(buildListEnvelope(result.data, pager.page, pager.limit));
  }, { permission: 'customers:read' })
);
