<?php

namespace Openguru\OpenCartFramework\Router;

use InvalidArgumentException;
use Openguru\OpenCartFramework\Exceptions\ActionNotFoundException;

class Router
{
    private array $routes;

    public function __construct(array $routes = [])
    {
        $this->routes = $routes;
    }

    public function loadRoutesFromFile(string $file): void
    {
        $this->routes = include $file;
    }

    /**
     * @param $action
     * @return string[]
     * @throws ActionNotFoundException
     */
    public function resolve($action): array
    {
        if (! $action) {
            throw new InvalidArgumentException('No action provided');
        }

        if (isset($this->routes[$action])) {
            return $this->routes[$action];
        }

        throw new ActionNotFoundException($action, 'Action "' . $action . '" not found.');
    }

    public function url(string $action, array $query = []): string
    {
        $query = array_merge([
            'route' => 'extension/tgshop/handle',
            'api_action' => $action,
        ], $query);

        return '/index.php?' . http_build_query($query);
    }
}
