<?php
declare(strict_types=1);

require_once __DIR__ . '/../includes/bootstrap.php';

dbnToolsRequireMethod('POST');
$input = dbnToolsJsonInput(2048);

$email = strtolower(trim((string)($input['email'] ?? '')));
$password = (string)($input['password'] ?? '');

if ($email === '') {
    dbnToolsError('Email is required.', 422, 'missing_email');
}
if ($password === '') {
    dbnToolsError('Password is required.', 422, 'missing_password');
}

try {
    $db = dbnToolsDb();
    $client = dbnToolsFetchClient($db);
    if (!$client || empty($client['is_active'])) {
        dbnToolsError('Do Better Norge Caveau workspace is not active.', 503, 'client_unavailable');
    }

    $user = dbnToolsFetchActiveClientUser($email, (int)$client['id'], $db);
} catch (DbnToolsHttpException $e) {
    dbnToolsError($e->getMessage(), $e->status, $e->errorCode, $e->extra);
} catch (Throwable $e) {
    error_log('DBN tools login error: ' . $e->getMessage());
    dbnToolsError('Caveau authentication is not available.', 503, 'auth_unavailable');
}

if (!$user || !password_verify($password, (string)$user['password_hash'])) {
    dbnToolsError('Email or password was not accepted.', 401, 'invalid_credentials');
}

$packageAccess = dbnToolsCanUsePackage((int)$client['id'], dbnToolsRequiredPackageSlug(), $db);
if (empty($packageAccess['ok'])) {
    dbnToolsError(
        (string)$packageAccess['message'],
        (int)$packageAccess['status'],
        (string)$packageAccess['code']
    );
}

session_regenerate_id(true);
$_SESSION['dbn_tools_authenticated'] = true;
$_SESSION['dbn_tools_authenticated_at'] = time();
$_SESSION['dbn_tools_anon_id'] = $_SESSION['dbn_tools_anon_id'] ?? bin2hex(random_bytes(16));
$_SESSION['dbn_tools_client_id'] = (int)$client['id'];
$_SESSION['dbn_tools_client_slug'] = (string)$client['slug'];
$_SESSION['dbn_tools_user_id'] = (int)$user['id'];
$_SESSION['dbn_tools_user_email'] = (string)$user['email'];
$_SESSION['dbn_tools_user_role'] = (string)$user['role'];
$_SESSION['dbn_tools_package_slug'] = dbnToolsRequiredPackageSlug();

dbnToolsRespond([
    'ok' => true,
    'authenticated' => true,
    'session' => dbnToolsAnonymousSessionId(),
    'user' => [
        'email' => (string)$user['email'],
        'role' => (string)$user['role'],
    ],
]);
