<?php

namespace NoahVet\Reef\Domain\Security\Model;

class Resource implements \Stringable, ResourceInterface
{
    final protected function __construct(
        protected ResourceType $resourceType,
        protected string $slug,
        protected string $resourceId,
    ) {
    }

    #[\Override]
    public function __toString(): string
    {
        return $this->slug;
    }

    public static function fromString(ResourceType|string $resourceType, string $resourceId): static
    {
        $resourceTypeObj = \is_string($resourceType) ? ResourceType::fromString($resourceType) : $resourceType;
        $resourceSlug = $resourceTypeObj->getSlug().':'.$resourceId;

        return new static($resourceTypeObj, $resourceSlug, $resourceId);
    }

    public static function fromSlug(string $slug): static
    {
        $lastColonPos = \strrpos($slug, ':');

        if (false === $lastColonPos) {
            throw new \InvalidArgumentException('The slug must contain a colon.');
        }

        $resourceType = ResourceType::fromString(\substr($slug, 0, $lastColonPos));
        $resourceId = \substr($slug, $lastColonPos + 1);

        return new static($resourceType, $slug, $resourceId);
    }

    #[\Override]
    public function getSlug(): string
    {
        return $this->slug;
    }

    #[\Override]
    public function getResourceType(): ResourceType
    {
        return $this->resourceType;
    }

    #[\Override]
    public function getResourceId(): string
    {
        return $this->resourceId;
    }
}
