<?php

declare(strict_types=1);

namespace App\Framework\Attributes;

use App\Framework\Core\ValueObjects\ClassName;
use App\Framework\Core\ValueObjects\MethodName;
use App\Framework\Http\Method;
use App\Framework\Router\RouteNameInterface;
use App\Framework\Router\ValueObjects\RoutePath;
use Attribute;

#[Attribute(Attribute::TARGET_METHOD | Attribute::IS_REPEATABLE)]
final readonly class Route implements RouteAttribute
{
    public function __construct(
        public string|RoutePath $path,
        public Method $method = Method::GET,
        public RouteNameInterface|string|null $name = null,
        /** @var array<int, string>|string */
        public array|string $subdomain = [],
    ) {
    }

    /**
     * Get the path as string for router compilation
     */
    public function getPathAsString(): string
    {
        return $this->path instanceof RoutePath
            ? $this->path->toString()
            : $this->path;
    }

    /**
     * Get the path as RoutePath object
     */
    public function getRoutePath(): RoutePath
    {
        return $this->path instanceof RoutePath
            ? $this->path
            : RoutePath::fromString($this->path);
    }

    /**
     * Transform this attribute into a CompiledRoute for the router
     */
    public function toCompiledRoute(ClassName $controller, MethodName $action): CompiledRoute
    {
        $routeName = $this->name instanceof RouteNameInterface
            ? $this->name->value
            : $this->name;

        return new CompiledRoute(
            path: $this->getPathAsString(),
            method: $this->method,
            controller: $controller->getFullyQualified(),
            action: $action->toString(),
            name: $routeName
        );
    }
}
