import { NextResponse } from 'next/server';
import { z } from 'zod';
import { withV1ErrorHandler } from '@server/middleware/v1Errors';
import { withApiKey, ApiKeyRequest } from '@server/middleware/withApiKey';
import { withV1Validation } from '@server/middleware/v1Validation';
import { ParsedRequest } from '@server/middleware/withValidation';
import { RouteContext } from '@server/middleware/withErrorHandler';
import { takeOverConversation } from '@server/services/conversations.service';

const takeoverSchema = z.object({
  agent_name: z.string().min(1, 'agent_name is required'),
});
type TakeoverInput = z.infer<typeof takeoverSchema>;

export const POST = withV1ErrorHandler(
  withApiKey(
    withV1Validation(takeoverSchema, async (req: ParsedRequest<TakeoverInput>, ctx: RouteContext) => {
      const apiReq = req as ParsedRequest<TakeoverInput> & ApiKeyRequest;
      const { id } = await ctx.params;
      const updated = await takeOverConversation(
        id,
        apiReq.apiKey.restaurantId,
        req.parsedBody.agent_name
      );
      return NextResponse.json({ data: updated });
    }),
    { permission: 'ai:write' }
  )
);
