<?php

declare(strict_types=1);

namespace App\Core;

use App\Repositories\UserRepository;

final class Auth
{
    public static function check(): bool
    {
        $user = Session::get('user');
        return is_array($user) && !empty($user['name']);
    }

    public static function user(): ?array
    {
        $user = Session::get('user');
        return is_array($user) ? $user : null;
    }

    public static function name(): string
    {
        $user = self::user();
        return (string) ($user['name'] ?? '');
    }

    public static function hospital(): string
    {
        $user = self::user();
        $fallback = \function_exists('default_hospital') ? \default_hospital() : 'njch';
        return (string) ($user['hospital'] ?? $fallback);
    }

    public static function attempt(string $username, string $password, string $hospitalCode = 'njch'): bool
    {
        $hospitalCode = \normalize_hospital_code($hospitalCode ?: \default_hospital());
        $repo = new UserRepository($hospitalCode);
        $user = $repo->findDashboardUserByLegacyPassword($username, $password);

        if (!$user) {
            return false;
        }

        Session::regenerate();
        Session::put('user', [
            'name' => (string) ($user['name'] ?? $username),
            'hospital' => $hospitalCode,
            'dashboard_role' => (int) ($user['dashboard_role'] ?? 0),
            'dashboard_role_fin' => (int) ($user['dashboard_role_fin'] ?? 0),
            'dashboard_role_revenue' => (int) ($user['dashboard_role_revenue'] ?? $user['dashboard_role'] ?? 0),
            'login_at' => date('c'),
        ]);

        return self::check();
    }

    public static function setHospital(string $hospitalCode): bool
    {
        $hospitalCode = \normalize_hospital_code($hospitalCode);
        $hospitals = \config('hospitals', []);
        if (!is_array($hospitals) || !array_key_exists($hospitalCode, $hospitals)) {
            return false;
        }

        $user = self::user();
        if (!$user) {
            return false;
        }

        $user['hospital'] = $hospitalCode;
        $user['hospital_changed_at'] = date('c');
        Session::put('user', $user);
        return true;
    }

    public static function logout(): void
    {
        self::clearRememberedState();
        Session::destroy();
    }

    public static function requireLogin(): void
    {
        if (!self::check()) {
            \redirect('index.php?page=login');
        }
    }

    private static function clearRememberedState(): void
    {
        Session::forget('user');
    }
}
