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

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

    await requireSection(req, 'telephone');
    await requirePlanFeature(restaurantId, 'voice_agent');

    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);
  })
);
