<?php

namespace app\service;

use support\Request;

class AdminAuthService
{
    private const SESSION_KEY = 'proofdb_admin_user_id';

    public function __construct(private readonly ?AdminUserRepository $users = null)
    {
    }

    public function authenticate(string $username, string $password): ?array
    {
        $username = trim($username);
        if ($username === '' || $password === '') {
            return null;
        }

        $user = $this->users()->findByUsername($username);
        if ($user === null || !password_verify($password, $user['password_hash'])) {
            return null;
        }

        unset($user['password_hash']);
        return $user;
    }

    public function login(Request $request, array $user): void
    {
        $request->session()->set(self::SESSION_KEY, (int) $user['id']);
        $this->users()->touchLastLogin((int) $user['id']);
    }

    public function logout(Request $request): void
    {
        $request->session()->delete(self::SESSION_KEY);
    }

    public function current(Request $request): ?array
    {
        $id = (int) $request->session()->get(self::SESSION_KEY, 0);
        if ($id <= 0) {
            return null;
        }

        $user = $this->users()->findById($id);
        if ($user === null) {
            $request->session()->delete(self::SESSION_KEY);
            return null;
        }

        unset($user['password_hash']);
        return $user;
    }

    private function users(): AdminUserRepository
    {
        return $this->users ?? new AdminUserRepository();
    }
}
