<?php
declare(strict_types=1);

namespace PpPhp\Core\Designer\Navigation;

final class DesignerRoute
{
    public function __construct(
        private readonly string $routeId,
        private readonly string $path,
        private readonly string $pageId,
        private readonly string $title = '',
        private readonly array $permissions = [],
        private readonly array $meta = []
    ) {}

    public static function create(string $routeId, string $path, string $pageId, string $title = ''): self
    {
        return new self($routeId, $path, $pageId, $title !== '' ? $title : self::humanize($pageId));
    }

    public static function fromArray(array $data): self
    {
        return new self(
            (string) ($data['routeId'] ?? $data['id'] ?? 'route'),
            (string) ($data['path'] ?? '/'),
            (string) ($data['pageId'] ?? $data['page'] ?? ''),
            (string) ($data['title'] ?? ''),
            (array) ($data['permissions'] ?? []),
            (array) ($data['meta'] ?? [])
        );
    }

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

    public function toArray(): array
    {
        return [
            'routeId' => $this->routeId,
            'id' => $this->routeId,
            'path' => $this->path,
            'pageId' => $this->pageId,
            'title' => $this->title,
            'permissions' => $this->permissions,
            'meta' => $this->meta,
        ];
    }

    private static function humanize(string $value): string
    {
        return ucwords(str_replace(['_', '-'], ' ', $value));
    }
}
