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

import { withAuth } from '@/lib/api/helpers';
import { parseBody } from '@/lib/api/route-helpers';
import { errorResponse } 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),
});

export const POST = withAuth(async (req) => {
  try {
    const body = await parseBody(req, schema);
    if (!OCR_MODELS[body.provider].includes(body.model)) {
      return NextResponse.json({ error: 'Invalid model' }, { status: 400 });
    }
    const result = await testProvider(body.provider, body.apiKey, body.model);
    return NextResponse.json(result);
  } catch (error) {
    return errorResponse(error);
  }
});
