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

import type { TokenResponse } from '@/types/auth';
import { normalizePortalLocale, pickPortalText } from '@/lib/i18n/core';
import { HttpError, REGISTER_REQUEST_TIMEOUT_MS, callAuthzService } 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 : 'registration 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;
      email?: string;
      password?: string;
    };
    const username = body.username?.trim() || '';
    const email = body.email?.trim() || '';
    const password = body.password || '';

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

    const response = await callAuthzService<TokenResponse>('/portal/register', {
      username,
      email,
      password,
    }, REGISTER_REQUEST_TIMEOUT_MS);

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