<?php

declare(strict_types=1);

namespace Lab;

final class Auth
{
    public function __construct(private array $config) {}

    public function attemptAdmin(string $username, string $password): bool
    {
        $expectedUser = (string) ($this->config['admin']['username'] ?? 'admin');
        $expectedPass = (string) ($this->config['admin']['password'] ?? '');
        if (! hash_equals($expectedUser, trim($username)) || ! hash_equals($expectedPass, $password)) {
            return false;
        }
        $_SESSION['lab_admin'] = 1;
        $_SESSION['lab_admin_name'] = (string) ($this->config['admin']['name'] ?? 'Admin');

        return true;
    }

    public function attemptPin(string $pin): bool
    {
        $expected = (string) ($this->config['admin']['pin'] ?? '1989');
        if (! hash_equals($expected, trim($pin))) {
            return false;
        }
        $_SESSION['lab_admin'] = 1;
        $_SESSION['lab_admin_name'] = (string) ($this->config['admin']['name'] ?? 'Admin');

        return true;
    }

    public function adminCheck(): bool
    {
        return ! empty($_SESSION['lab_admin']);
    }

    public function requireAdmin(): void
    {
        if (! $this->adminCheck()) {
            View::redirect('/studio/login');
        }
    }

    public function logout(): void
    {
        unset($_SESSION['lab_admin'], $_SESSION['lab_admin_name']);
    }

    public function adminName(): string
    {
        return (string) ($_SESSION['lab_admin_name'] ?? '');
    }
}
