import { NextResponse } from 'next/server';
import { withErrorHandler, RouteContext } from '@server/middleware/withErrorHandler';
import { withAuth, requireSection, AuthedRequest } from '@server/middleware/withAuth';
import { withValidationAuthed } from '@server/middleware/withValidation';
import { updateAgentSchema } from '@server/validators/ai-agents.validator';
import { getAgent, updateAgent, deleteAgent } from '@server/services/ai-agents.service';
import { requirePlanFeature } from '@server/utils/features';

export const GET = withErrorHandler(
  withAuth(async (req: AuthedRequest, context: RouteContext) => {
    const { id } = await context.params;
    const { restaurantId, branchId } = req.session;
    await requireSection(req, 'ai_config');
    await requirePlanFeature(restaurantId!, 'chat_agent');
    const agent = await getAgent(id, restaurantId!, branchId ?? null);
    return NextResponse.json({ agent });
  })
);

export const PATCH = withErrorHandler(
  withAuth(
    withValidationAuthed(updateAgentSchema, async (req, context) => {
      const { id } = await context.params;
      const { restaurantId, branchId } = req.session;
      await requireSection(req, 'ai_config', 'update');
      await requirePlanFeature(restaurantId!, 'chat_agent');
      const agent = await updateAgent(id, restaurantId!, req.parsedBody as Record<string, unknown>, branchId ?? null);
      return NextResponse.json({ agent });
    })
  )
);

export const DELETE = withErrorHandler(
  withAuth(async (req: AuthedRequest, context: RouteContext) => {
    const { id } = await context.params;
    const { restaurantId, branchId } = req.session;
    await requireSection(req, 'ai_config', 'delete');
    await requirePlanFeature(restaurantId!, 'chat_agent');
    await deleteAgent(id, restaurantId!, branchId ?? null);
    return NextResponse.json({ success: true });
  })
);
