<?php
declare(strict_types=1);

namespace App;

use App\Repositories\Container;

class Auth
{
    public static function user(): ?array
    {
        $id = $_SESSION['user_id'] ?? null;
        if (!$id) return null;
        return Container::users()->find($id);
    }

    public static function check(): bool
    {
        return self::user() !== null;
    }

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

    public static function hasRole(array $roles): bool
    {
        $r = self::role();
        return $r !== null && in_array($r, $roles, true);
    }

    public static function login(array $user): void
    {
        Session::regenerate();
        $_SESSION['user_id'] = $user['id'];
        $_SESSION['user_role'] = $user['role'];
    }

    public static function logout(): void
    {
        unset($_SESSION['user_id'], $_SESSION['user_role']);
        Session::regenerate();
    }

    public static function attempt(string $username, string $password): ?array
    {
        $users = Container::users();
        $user = $users->findByUsername($username);
        if (!$user || empty($user['password_hash']) || empty($user['is_active'])) return null;
        if (!password_verify($password, $user['password_hash'])) return null;
        return $user;
    }
}
