<?php

/*
 * This file is part of the VITICORE2 package.
 *
 * (c) CP Creation <web@cpcreation.fr>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace CpCreation\VitiTheme\Theme;

final readonly class ThemeDefinition
{
    /**
     * @param array<string, mixed> $metadata
     */
    public function __construct(
        public string $name,
        public string $label,
        public string $version,
        public string $path,
        public array $metadata,
        public string $templatesDirectory = 'templates',
        public string $assetsDirectory = 'assets',
        public ?string $translationsDirectory = 'translations',
        public ?string $publicDirectory = null,
        public ?string $package = null,
    ) {
    }

    public function templatesPath(): string
    {
        return $this->resolveDirectory($this->templatesDirectory);
    }

    public function templatePath(string $template): string
    {
        return $this->join($this->templatesPath(), $template);
    }

    public function assetsPath(): string
    {
        return $this->resolveDirectory($this->assetsDirectory);
    }

    public function assetPath(string $asset): string
    {
        return $this->join($this->assetsPath(), $asset);
    }

    public function translationsPath(): ?string
    {
        if (null === $this->translationsDirectory) {
            return null;
        }

        return $this->resolveDirectory($this->translationsDirectory);
    }

    public function publicPath(?string $asset = null): ?string
    {
        if (null === $this->publicDirectory) {
            return null;
        }

        return $this->join($this->resolveDirectory($this->publicDirectory), $asset ?? '');
    }

    private function resolveDirectory(string $directory): string
    {
        if ('' === $directory || '.' === $directory) {
            return mb_rtrim($this->path, '/');
        }

        if (str_starts_with($directory, '/') || 1 === preg_match('#^[A-Za-z]:[\\\\/]#', $directory)) {
            return mb_rtrim($directory, '/');
        }

        return $this->join($this->path, $directory);
    }

    private function join(string $basePath, string $relativePath): string
    {
        $basePath = mb_rtrim($basePath, '/');
        $relativePath = mb_trim($relativePath, '/');

        if ('' === $relativePath) {
            return $basePath;
        }

        return $basePath.'/'.$relativePath;
    }
}
