<?php

declare(strict_types=1);

namespace App\Framework\Console\Security;

use App\Framework\Environment\Environment;
use App\Framework\Environment\EnvKey;

final readonly class EnvironmentUserProvider implements UserProvider
{
    public function __construct(
        private Environment $environment
    ) {
    }

    public function getCurrentUser(): ConsoleUser
    {
        $userId = $this->environment->get(EnvKey::CONSOLE_USER_ID);
        $userName = $this->environment->get(EnvKey::CONSOLE_USER_NAME);
        $userRole = $this->environment->get(EnvKey::CONSOLE_USER_ROLE, 'user');

        if (! $userId || ! $userName) {
            return ConsoleUser::anonymous();
        }

        $permissions = $this->getPermissionsForRole($userRole);
        $roles = [$userRole];

        return new ConsoleUser(
            id: $userId,
            name: $userName,
            permissions: $permissions,
            roles: $roles
        );
    }

    public function getUserById(string $id): ?ConsoleUser
    {
        $currentUser = $this->getCurrentUser();

        return $currentUser->id === $id ? $currentUser : null;
    }

    public function authenticateUser(array $credentials): ?ConsoleUser
    {
        // For environment-based auth, we just return the current user
        // In a real implementation, this might validate API keys or tokens
        return $this->getCurrentUser();
    }

    public function isAuthenticated(): bool
    {
        $userId = $this->environment->get(EnvKey::CONSOLE_USER_ID);

        return ! empty($userId) && $userId !== 'anonymous';
    }

    private function getPermissionsForRole(string $role): array
    {
        return match (strtolower($role)) {
            'admin', 'administrator' => Permission::cases(), // All permissions
            'developer', 'dev' => [
                Permission::READ,
                Permission::WRITE,
                Permission::EXECUTE,
                Permission::ANALYTICS_READ,
                Permission::HEALTH_CHECK,
                Permission::DATABASE_READ,
                Permission::PERFORMANCE_READ,
            ],
            'operator', 'ops' => [
                Permission::READ,
                Permission::EXECUTE,
                Permission::ANALYTICS_READ,
                Permission::HEALTH_CHECK,
                Permission::PERFORMANCE_READ,
                Permission::CACHE_MANAGE,
            ],
            'readonly', 'reader' => [
                Permission::READ,
                Permission::ANALYTICS_READ,
                Permission::HEALTH_CHECK,
                Permission::PERFORMANCE_READ,
            ],
            'guest', 'anonymous' => [
                Permission::READ,
                Permission::EXECUTE,
            ],
            default => [
                Permission::READ,
                Permission::EXECUTE,
            ]
        };
    }
}
