import { NextResponse } from 'next/server';
import { withErrorHandler } from '@server/middleware/withErrorHandler';
import { withAuth, AuthedRequest } from '@server/middleware/withAuth';
import { listCallSessions } from '@server/services/call-sessions.service';
import { ValidationError } from '@server/errors';

export const GET = withErrorHandler(
  withAuth(async (req: AuthedRequest) => {
    const { restaurantId } = req.session;
    if (!restaurantId) throw new ValidationError('Restaurant context required');

    const url = new URL(req.url);

    const filters = {
      status: url.searchParams.get('status') || undefined,
      direction: url.searchParams.get('direction') || undefined,
      agentId: url.searchParams.get('agentId') || undefined,
      dateFrom: url.searchParams.get('dateFrom') || undefined,
      dateTo: url.searchParams.get('dateTo') || undefined,
      page: parseInt(url.searchParams.get('page') || '1', 10),
      limit: parseInt(url.searchParams.get('limit') || '20', 10),
    };

    const result = await listCallSessions(restaurantId, filters);
    return NextResponse.json(result);
  })
);
