<?php
// =============================================================
//  api/v1/auth/_helpers.php
//
//  Shared by login.php and verify_2fa.php — the two endpoints that can
//  end in a fully-established session. Keeping "what a successful login
//  returns" in one place avoids the two ever drifting apart (the same
//  motivation as include/session_setup.php's own doc comment).
// =============================================================

/**
 * The user-profile shape returned to the client on every successful auth
 * response. Takes $conn to resolve `totp_enabled` (staff/'users' table
 * only — see include/Totp.php) so the mobile client always knows current
 * 2FA state from a profile it already fetches, rather than a separate
 * status endpoint.
 */
function api_build_profile(mysqli $conn, Account $account): array
{
    require_once __DIR__ . '/../../../include/Totp.php';
    $table = $account->getTable();
    $totpEnabled = $table === 'users' && Totp::isEnabledFor($conn, $account->getId());

    return [
        'id'              => $account->getId(),
        'table'           => $table,
        'user_type'       => $account->getUserType(),
        'firstname'       => $account->getFirstname(),
        'surname'         => $account->getSurname(),
        'full_name'       => $account->getFullName(),
        'email'           => $account->getEmail(),
        'phone'           => $account->getPhone(),
        'profile'         => $account->getProfile(),
        'role_name'       => $_SESSION['role_name']       ?? $account->getUserType(),
        'role_display'    => $_SESSION['role_display']    ?? $account->getUserType(),
        'permissions'     => $_SESSION['permissions']     ?? [],
        'department_id'   => $_SESSION['department_id']   ?? null,
        'department_name' => $_SESSION['department_name'] ?? null,
        'unit_ids'        => $_SESSION['unit_ids']         ?? [],
        'unit_names'      => $_SESSION['unit_names']       ?? [],
        'totp_enabled'    => $totpEnabled,
    ];
}

/**
 * Finalizes a login after credentials (and 2FA, if applicable) are confirmed:
 * hydrates the request context (include/session_setup.php), stamps
 * last_login, writes the audit log (staff only — mirrors
 * establishUserSession()'s web-login side effects), issues a bearer token,
 * and returns the {token, user} payload the client needs.
 */
function api_finalize_login(
    mysqli $conn,
    PermissionManager $perm_manager,
    ApiTokenManager $token_manager,
    Account $account,
    ?string $deviceLabel,
    string $platform
): array {
    $table = $account->getTable();
    hydrateRequestContext($conn, $perm_manager, $account->toArray(), $table, $account->getUserType());

    $id  = $account->getId();
    $upd = $conn->prepare("UPDATE `{$table}` SET last_login = NOW() WHERE id = ?");
    $upd->bind_param('i', $id);
    $upd->execute();
    $upd->close();

    if ($table === 'users') {
        $perm_manager->logAudit(
            $id, 'login', 'user', $id, null,
            json_encode([
                'via'               => 'mobile_api',
                'role'              => $_SESSION['role_name'] ?? null,
                'permissions_count' => count($_SESSION['permissions'] ?? []),
                'department_id'     => $_SESSION['department_id'] ?? null,
                'unit_ids'          => $_SESSION['unit_ids'] ?? [],
            ])
        );
    }

    $token = $token_manager->issue($table, $id, $deviceLabel, $platform);

    return ['token' => $token, 'user' => api_build_profile($conn, $account)];
}

/** Normalizes a client-supplied platform string to one of the columns' enum values. */
function api_normalize_platform(?string $platform): string
{
    $platform = strtolower(trim((string)$platform));
    return in_array($platform, ['android', 'ios', 'web'], true) ? $platform : 'other';
}
