import { NextResponse } from 'next/server';
import { withErrorHandler, RouteContext } from '@server/middleware/withErrorHandler';
import { withAuth, 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';

export const GET = withErrorHandler(
  withAuth(async (req: AuthedRequest, context: RouteContext) => {
    const { id } = await context.params;
    const { restaurantId, branchId } = req.session;
    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;
      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 deleteAgent(id, restaurantId!, branchId ?? null);
    return NextResponse.json({ success: true });
  })
);
