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';

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 : 'login 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;
    };
    const username = body.username?.trim() || '';
    const password = body.password || '';

    if (!username || !password) {
      return NextResponse.json({
        detail: pickPortalText(locale, '用户名和密码不能为空', 'Username and password are required'),
      }, { status: 400 });
    }

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

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

    return NextResponse.json(normalizeTokenResponse(response, routing));
  } catch (error) {
    const status = errorStatus(error);
    const detail = status === 404 || status === 401
      ? pickPortalText(locale, '用户名或密码错误', 'Incorrect username or password')
      : errorDetail(error);
    return NextResponse.json({ detail }, { status: status === 404 ? 401 : status });
  }
}
