import { NextResponse } from 'next/server';
import { withErrorHandler } from '@server/middleware/withErrorHandler';
import { withAuth, requireSection, requireSectionAny, AuthedRequest } from '@server/middleware/withAuth';
import { withValidationAuthed } from '@server/middleware/withValidation';
import { createAgentSchema } from '@server/validators/ai-agents.validator';
import { listAgents, createAgent } from '@server/services/ai-agents.service';
import { requirePlanFeature } from '@server/utils/features';

export const GET = withErrorHandler(
  withAuth(async (req: AuthedRequest) => {
    const { restaurantId, branchId } = req.session;
    await requireSectionAny(req, ['ai_config', 'telephone']);
    await requirePlanFeature(restaurantId!, 'chat_agent');
    const url = new URL(req.url);
    const scope = url.searchParams.get('scope');
    const effectiveBranchId = scope === 'restaurant' ? null : (branchId ?? null);
    const agents = await listAgents(restaurantId!, effectiveBranchId);
    return NextResponse.json({ agents });
  })
);

export const POST = withErrorHandler(
  withAuth(
    withValidationAuthed(createAgentSchema, async (req) => {
      const { restaurantId, branchId } = req.session;
      await requireSection(req, 'ai_config', 'create');
      await requirePlanFeature(restaurantId!, 'chat_agent');
      const agent = await createAgent(restaurantId!, req.parsedBody as Record<string, unknown>, branchId ?? null);
      return NextResponse.json({ agent }, { status: 201 });
    })
  )
);
