import { NextRequest, NextResponse } from 'next/server';

import type { TokenResponse } from '@/types/auth';
import { normalizePortalLocale, pickPortalText } from '@/lib/i18n/core';
import { HttpError, callDeployControl, callInstanceApi, normalizeTokenResponse } from '@/lib/runtime-control';

const PROVIDER_ONBOARDING_TIMEOUT_MS = 120000;
const KNOWN_PROVIDERS = new Set([
  'anthropic',
  'openai',
  'openrouter',
  'deepseek',
  'groq',
  'zhipu',
  'dashscope',
  'vllm',
  'gemini',
  'moonshot',
  'minimax',
  'aihubmix',
  'siliconflow',
  'volcengine',
]);
const API_KEY_OPTIONAL_PROVIDERS = new Set(['vllm']);

function errorStatus(error: unknown): number {
  if (error instanceof HttpError) {
    return error.status;
  }
  return 500;
}

function errorDetail(error: unknown): string {
  if (error instanceof HttpError) {
    return error.message;
  }
  return error instanceof Error ? error.message : 'provider onboarding failed';
}

export async function POST(request: NextRequest) {
  const locale = normalizePortalLocale(
    request.cookies.get('beaver_locale')?.value ||
    request.headers.get('accept-language')
  );

  try {
    const body = (await request.json()) as {
      username?: string;
      password?: string;
      provider?: string;
      model?: string;
      api_key?: string;
      api_base?: string;
    };
    const username = body.username?.trim() || '';
    const password = body.password || '';
    const provider = body.provider?.trim() || '';
    const model = body.model?.trim() || '';
    const apiKey = body.api_key?.trim() || '';
    const apiBase = body.api_base?.trim() || '';

    if (!username || !password) {
      return NextResponse.json({
        detail: pickPortalText(locale, '用户名和密码不能为空', 'Username and password are required'),
      }, { status: 400 });
    }
    if (!KNOWN_PROVIDERS.has(provider)) {
      return NextResponse.json({
        detail: pickPortalText(locale, '请选择有效的模型提供商', 'Choose a valid model provider'),
      }, { status: 400 });
    }
    if (!model) {
      return NextResponse.json({
        detail: pickPortalText(locale, '模型名称不能为空', 'Model name is required'),
      }, { status: 400 });
    }
    if (!API_KEY_OPTIONAL_PROVIDERS.has(provider) && !apiKey) {
      return NextResponse.json({
        detail: pickPortalText(locale, 'API Key 不能为空', 'API key is required'),
      }, { status: 400 });
    }
    if (API_KEY_OPTIONAL_PROVIDERS.has(provider) && !apiKey && !apiBase) {
      return NextResponse.json({
        detail: pickPortalText(locale, '本地模型至少需要 API Base', 'Local models require at least an API base URL'),
      }, { status: 400 });
    }

    const initialRouting = await callDeployControl<{
      api_base_url?: string;
      frontend_base_url?: string;
      public_url?: string;
    }>('/api/instances/resolve', { username });

    await callInstanceApi<TokenResponse>(initialRouting.api_base_url || '', '/api/auth/login', {
      username,
      password,
    });

    const configuredRouting = await callDeployControl<{
      api_base_url?: string;
      frontend_base_url?: string;
      public_url?: string;
    }>('/api/instances/configure-provider', {
      username,
      provider,
      model,
      api_key: apiKey,
      api_base: apiBase,
    }, PROVIDER_ONBOARDING_TIMEOUT_MS);

    const response = await callInstanceApi<TokenResponse>(configuredRouting.api_base_url || '', '/api/auth/login', {
      username,
      password,
    });

    return NextResponse.json(normalizeTokenResponse(response, configuredRouting));
  } catch (error) {
    return NextResponse.json({ detail: errorDetail(error) }, { status: errorStatus(error) });
  }
}
