<?php

declare(strict_types=1);

namespace PpPhp\Core\Platform\Metadata\Builders;

use InvalidArgumentException;
use PpPhp\Core\Platform\Metadata\Collections\PlatformTagCollection;
use PpPhp\Core\Platform\Metadata\ValueObjects\PlatformCategory;
use PpPhp\Core\Platform\Metadata\ValueObjects\PlatformMetadata;
use PpPhp\Core\Platform\Metadata\ValueObjects\PlatformTag;
use PpPhp\Core\Platform\Metadata\ValueObjects\PlatformVersionInfo;

/**
 * Builds immutable PlatformMetadata objects.
 *
 * This builder intentionally lives outside PlatformMetadata so the value object
 * remains dependency-light and easy to serialize/test.
 *
 * @since PPphp Platform 2.0.0-dev
 */
final class MetadataBuilder
{
    private string $name = 'Unnamed Asset';
    private string $description = '';
    private string $category = PlatformCategory::OTHER;
    private string $icon = '';
    private string $author = 'PPphp Team';
    private ?PlatformVersionInfo $version = null;
    private PlatformTagCollection $tags;

    private function __construct()
    {
        $this->tags = new PlatformTagCollection();
    }

    public static function create(): self
    {
        return new self();
    }

    public function name(string $name): self
    {
        $name = trim($name);

        if ($name === '') {
            throw new InvalidArgumentException('Metadata name cannot be empty.');
        }

        $this->name = $name;
        return $this;
    }

    public function description(string $description): self
    {
        $this->description = trim($description);
        return $this;
    }

    public function category(string $category): self
    {
        if (!PlatformCategory::isValid($category)) {
            throw new InvalidArgumentException(sprintf('Invalid metadata category: %s', $category));
        }

        $this->category = $category;
        return $this;
    }

    public function icon(string $icon): self
    {
        $this->icon = trim($icon);
        return $this;
    }

    public function author(string $author): self
    {
        $author = trim($author);
        $this->author = $author !== '' ? $author : 'PPphp Team';
        return $this;
    }

    public function version(PlatformVersionInfo $version): self
    {
        $this->version = $version;
        return $this;
    }

    public function addTag(PlatformTag|string $tag): self
    {
        if (is_string($tag)) {
            $tag = new PlatformTag($tag);
        }

        $this->tags->add($tag);
        return $this;
    }

    public function tags(PlatformTagCollection $tags): self
    {
        $this->tags = $tags;
        return $this;
    }

    public function build(): PlatformMetadata
    {
        return new PlatformMetadata(
            $this->name,
            $this->description,
            $this->category,
            $this->icon,
            $this->author,
            $this->version,
            $this->tags
        );
    }
}
