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

import {
  SESSION_COOKIE_NAME,
  getRequestHost,
  readBackendSessionCookie,
  sessionCookieDomain,
} from '@/services/auth';
import { OpenApiHttpError } from '@/services/openApiFetch';

import { reportApiError } from '@/utils/apiError';

import { authLogin } from '@/generated/azopus-api';

// Spring Security's messages for rejected credentials (as the admin app's login handles them).
const AUTH_FAILURE_MESSAGES = ['Bad credentials', 'User is disabled', 'User account is locked'];

export async function POST(request: NextRequest) {
  try {
    const body: unknown = await request.json();
    const email =
      body && typeof body === 'object' && 'email' in body && typeof body.email === 'string'
        ? body.email.trim()
        : '';
    const password =
      body && typeof body === 'object' && 'password' in body && typeof body.password === 'string'
        ? body.password
        : '';

    if (!email || !password) {
      return NextResponse.json(
        { error: 'Az e-mail és a jelszó megadása kötelező.' },
        { status: 400 }
      );
    }

    const response = await authLogin({ username: email, password }, { cache: 'no-store' });

    // The backend answers without a body and sets the session as an HttpOnly cookie shared by its
    // subdomains. It is stored as the backend set it (name, Domain, SameSite), so the admin app
    // receives the same cookie and no second, host-only copy is created. Where the browser would
    // refuse that Domain (localhost in development), it is stored for this host only.
    const session = readBackendSessionCookie(response.headers);
    if (!session) {
      console.warn('[login API] successful response without a session cookie');
      return NextResponse.json(
        { error: 'A belépés nem adott vissza munkamenetet.' },
        { status: 502 }
      );
    }

    const result = NextResponse.json({ ok: true });
    const domain = sessionCookieDomain(session.domain, getRequestHost(request.headers));
    result.cookies.set(SESSION_COOKIE_NAME, session.value, {
      httpOnly: true,
      secure: true,
      sameSite: session.sameSite ?? 'lax',
      path: session.path ?? '/',
      ...(domain ? { domain } : {}),
      ...(session.maxAge !== undefined ? { maxAge: session.maxAge } : {}),
      ...(session.expires ? { expires: session.expires } : {}),
    });
    return result;
  } catch (error) {
    // openApiFetch throws on a non-2xx answer: rejected credentials are a failed login, not an
    // outage. The backend answers them with 500 and a Spring Security message for now.
    if (
      error instanceof OpenApiHttpError &&
      (error.status === 401 ||
        error.status === 403 ||
        AUTH_FAILURE_MESSAGES.some((message) => error.message.includes(`"${message}"`)))
    ) {
      console.warn(`[login API] request failed with HTTP ${error.status}`);
      return NextResponse.json({ error: 'Sikertelen belépés.' }, { status: 401 });
    }
    reportApiError(error, 'Login request failed:');
    return NextResponse.json({ error: 'A belépés most nem érhető el.' }, { status: 502 });
  }
}
