import { NextResponse } from 'next/server';
import { withErrorHandler } from '@server/middleware/withErrorHandler';
import { withAuth, requireSection, AuthedRequest } from '@server/middleware/withAuth';
import { syncOpenRouterModels, verifyKey } from '@server/services/openrouter-sync.service';
import { resolveApiKey } from '@server/services/provider-keys.service';

export const POST = withErrorHandler(
  withAuth(async (req: AuthedRequest) => {
    await requireSection(req, 'ai_config', 'update');
    const { restaurantId } = req.session;
    const apiKey = restaurantId
      ? await resolveApiKey(restaurantId, 'openrouter')
      : process.env.OPENROUTER_API_KEY ?? null;

    if (!apiKey) {
      return NextResponse.json(
        {
          success: false, fetched: 0, upserted: 0, skipped: 0,
          error: 'No OpenRouter API key configured. Set one in Settings → API Keys before syncing models.',
        },
        { status: 400 }
      );
    }
    const verify = await verifyKey(apiKey);
    if (!verify.ok) {
      return NextResponse.json(
        { success: false, fetched: 0, upserted: 0, skipped: 0, error: verify.error },
        { status: 400 }
      );
    }

    const result = await syncOpenRouterModels(apiKey);
    if (result.error) {
      return NextResponse.json({ success: false, ...result }, { status: 502 });
    }
    return NextResponse.json({ success: true, ...result });
  })
);
