<?php
declare(strict_types=1);

namespace Admin;

final class AdminAccess
{
    /** @return array{allowed: bool, authenticated: bool, status: int, action: string, location?: string} */
    public static function decision(?array $user): array
    {
        if ($user === null || $user === []) {
            return [
                'allowed' => false,
                'authenticated' => false,
                'status' => 401,
                'action' => 'unauthorized',
            ];
        }

        $role = strtolower(trim((string) ($user['role'] ?? '')));
        $status = strtolower(trim((string) ($user['status'] ?? '')));
        $hasValidId = filter_var($user['id'] ?? null, FILTER_VALIDATE_INT, ['options' => ['min_range' => 1]]) !== false;

        if (!$hasValidId || $status !== 'active' || !in_array($role, ['admin', 'moderator'], true)) {
            return [
                'allowed' => false,
                'authenticated' => true,
                'status' => 403,
                'action' => 'forbidden',
            ];
        }

        return [
            'allowed' => true,
            'authenticated' => true,
            'status' => 200,
            'action' => 'allow',
        ];
    }

    public static function sessionUser(): ?array
    {
        $user = $_SESSION['auth_user'] ?? null;
        return is_array($user) && $user !== [] ? $user : null;
    }
}
