<?php
/// file: app/Core/Auth.php

declare(strict_types=1);

namespace App\Core;

use App\Models\Admin;

final class Auth
{
    private const SESSION_KEY = 'admin_id';

    public function attempt(string $email, string $password): bool
    {
        $admin = Admin::findByEmail($email);
        if ($admin === null) {
            return false;
        }
        $hash = (string) ($admin['password_hash'] ?? '');
        if (! password_verify($password, $hash)) {
            return false;
        }
        Session::set(self::SESSION_KEY, (int) $admin['id']);
        Session::regenerate();
        return true;
    }

    public function logout(): void
    {
        Session::remove(self::SESSION_KEY);
    }

    public function check(): bool
    {
        return Session::get(self::SESSION_KEY) !== null;
    }

    public function id(): ?int
    {
        $v = Session::get(self::SESSION_KEY);
        return is_int($v) ? $v : (is_numeric($v) ? (int) $v : null);
    }
}
