<?php

declare(strict_types=1);

namespace NoahVet\Reef\Phpunit\Fixture;

use NoahVet\Reef\Security\User\ReefOAuthUser;

class ReefTokenFixture
{
    /**
     * @var PermissionFixture[]
     */
    protected array $permissions;

    /**
     * @param PermissionFixture[] $perms
     */
    public function __construct(
        protected string $token,
        protected ?ReefOAuthUser $user,
        ?array $perms = null,
        protected bool $isSuperAdmin = false,
    ) {
        $this->permissions = $perms ?? [];
    }

    public function getToken(): string
    {
        return $this->token;
    }

    public function getUser(): ?ReefOAuthUser
    {
        return $this->user;
    }

    /**
     * @return PermissionFixture[]
     */
    public function getAllPermissions(): array
    {
        return $this->permissions;
    }

    public function isSuperAdmin(): bool
    {
        return $this->isSuperAdmin;
    }

    /**
     * @return list<PermissionFixture>
     */
    public function getPermissionsByResourceType(string $resourceType): array
    {
        return \array_values(
            \array_filter(
                $this->permissions,
                fn (PermissionFixture $permFixture) => $permFixture->getResourceType()->getSlug() === $resourceType,
            ),
        );
    }

    public function getPermissions(string $resource): ?PermissionFixture
    {
        $fixtures = \array_values(
            \array_filter(
                $this->permissions,
                fn (PermissionFixture $permFixture) => $permFixture->getTargetSlug() === $resource,
            ),
        );

        return $fixtures[0] ?? null;
    }

    /**
     * @param array{
     *     token: string,
     *     isAdmin: bool,
     *     userId?: string,
     *     userEmail?: string,
     *     permissions: PermissionFixture[],
     * } $fixtureDefinition
     */
    public static function build(array $fixtureDefinition): self
    {
        if (isset($fixtureDefinition['userId'])) {
            $reefUser = new ReefOAuthUser(
                $fixtureDefinition['userId'],
                $fixtureDefinition['userEmail'] ?? null,
            );
        } else {
            $reefUser = null;
        }

        return new self(
            $fixtureDefinition['token'],
            $reefUser,
            $fixtureDefinition['permissions'],
            $fixtureDefinition['isAdmin'],
        );
    }
}
