import { NextResponse } from 'next/server';
import { z } from 'zod';

import { withAuth, withPermission } from '@/lib/api/helpers';
import { parseBody } from '@/lib/api/route-helpers';
import { errorResponse, ValidationError } from '@/lib/errors';
import { OCR_MODELS } from '@/lib/services/ocr-config.service';
import { testProvider } from '@/lib/services/ocr-providers';

const schema = z.object({
  provider: z.enum(['openai', 'claude']),
  model: z.string().min(1),
  apiKey: z.string().min(1),
});

// `manage_settings`-gated for parity with the parent OCR settings route -
// triggers outbound AI provider auth requests using a caller-supplied key.
export const POST = withAuth(
  withPermission('admin', 'manage_settings', async (req) => {
    try {
      const body = await parseBody(req, schema);
      if (!OCR_MODELS[body.provider].includes(body.model)) {
        throw new ValidationError('Invalid model');
      }
      const result = await testProvider(body.provider, body.apiKey, body.model);
      return NextResponse.json(result);
    } catch (error) {
      return errorResponse(error);
    }
  }),
);
