<?php
declare(strict_types=1);

namespace ROITheme\Admin\CustomCSSManager\Domain\Entities;

use ROITheme\Admin\CustomCSSManager\Domain\ValueObjects\SnippetId;
use ROITheme\Admin\CustomCSSManager\Domain\ValueObjects\CSSCode;
use ROITheme\Admin\CustomCSSManager\Domain\ValueObjects\LoadType;
use ROITheme\Shared\Domain\Exceptions\ValidationException;

/**
 * Entidad de dominio para snippet CSS (contexto Admin)
 *
 * Responsabilidad: Reglas de negocio para ADMINISTRAR snippets
 */
final class CSSSnippet
{
    private function __construct(
        private readonly SnippetId $id,
        private readonly string $name,
        private readonly string $description,
        private readonly CSSCode $css,
        private readonly LoadType $loadType,
        private readonly array $pages,
        private readonly bool $enabled,
        private readonly int $order
    ) {}

    /**
     * Factory method desde array (BD)
     */
    public static function fromArray(array $data): self
    {
        return new self(
            SnippetId::fromString($data['id']),
            $data['name'],
            $data['description'] ?? '',
            CSSCode::fromString($data['css']),
            LoadType::fromString($data['type']),
            $data['pages'] ?? ['all'],
            $data['enabled'] ?? true,
            $data['order'] ?? 100
        );
    }

    /**
     * Valida que el snippet pueda ser guardado
     * @throws ValidationException
     */
    public function validate(): void
    {
        if (empty($this->name)) {
            throw new ValidationException('El nombre del snippet es requerido');
        }

        if (strlen($this->name) > 100) {
            throw new ValidationException('El nombre no puede exceder 100 caracteres');
        }

        // CSS ya validado en Value Object CSSCode
    }

    /**
     * Convierte a array para persistencia
     */
    public function toArray(): array
    {
        return [
            'id' => $this->id->value(),
            'name' => $this->name,
            'description' => $this->description,
            'css' => $this->css->value(),
            'type' => $this->loadType->value(),
            'pages' => $this->pages,
            'enabled' => $this->enabled,
            'order' => $this->order,
        ];
    }

    // Getters
    public function id(): SnippetId
    {
        return $this->id;
    }

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

    public function css(): CSSCode
    {
        return $this->css;
    }

    public function loadType(): LoadType
    {
        return $this->loadType;
    }

    public function pages(): array
    {
        return $this->pages;
    }

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

    public function order(): int
    {
        return $this->order;
    }
}
