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 { listConversations } from '@server/services/conversations.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 listConversations({
      restaurantId: req.apiKey.restaurantId,
      branchId: url.searchParams.get('branch_id') ?? undefined,
      status: url.searchParams.get('status') ?? undefined,
      channel: url.searchParams.get('channel') ?? undefined,
      search: url.searchParams.get('search') ?? undefined,
      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,
    });
    return NextResponse.json(buildListEnvelope(result.data, pager.page, pager.limit));
  }, { permission: 'ai:read' })
);
