<?php
declare(strict_types=1);

namespace App\Modules\Auth;

use App\Core\Support\Session;
use App\Modules\Users\UserRepository;

final class AuthService
{
    private const SESSION_USER_KEY = 'auth_user';

    public function __construct(private readonly UserRepository $users)
    {
    }

    public function attempt(string $email, string $password): bool
    {
        $storedUser = $this->users->findByEmail($email);
        if ($storedUser === null) {
            return false;
        }

        $storedHash = (string) ($storedUser['password_hash'] ?? '');
        if ($storedHash === '' || !password_verify($password, $storedHash)) {
            return false;
        }

        Session::regenerate();

        $_SESSION[self::SESSION_USER_KEY] = [
            'id' => (int) ($storedUser['id'] ?? 0),
            'name' => (string) ($storedUser['name'] ?? ''),
            'email' => strtolower((string) ($storedUser['email'] ?? '')),
            'login_at' => date(DATE_ATOM),
        ];

        return true;
    }

    public function check(): bool
    {
        return isset($_SESSION[self::SESSION_USER_KEY]) && is_array($_SESSION[self::SESSION_USER_KEY]);
    }

    /**
     * @return array<string, mixed>|null
     */
    public function user(): ?array
    {
        if (!$this->check()) {
            return null;
        }

        /** @var array<string, mixed> $user */
        $user = $_SESSION[self::SESSION_USER_KEY];
        return $user;
    }

    public function logout(): void
    {
        unset($_SESSION[self::SESSION_USER_KEY]);
        Session::regenerate();
    }
}
