<?php

namespace App\Support;

use App\Filament\Pages\BaselineCompareLanding;
use App\Filament\Resources\ProviderConnectionResource;
use App\Models\ManagedEnvironment;
use App\Models\ProviderConnection;
use App\Models\Workspace;
use App\Support\Links\RequiredPermissionsLinks;
use App\Support\Workspaces\WorkspaceContext;

final class ManagedEnvironmentLinks
{
    /**
     * @param  array<string, mixed>  $query
     */
    public static function indexUrl(Workspace|ManagedEnvironment|null $scope = null, array $query = []): string
    {
        $workspace = self::workspaceFromScope($scope);

        if (! $workspace instanceof Workspace) {
            return url('/admin');
        }

        return self::withQuery(route('admin.workspace.managed-environments.index', [
            'workspace' => self::workspaceRouteKey($workspace),
        ]), $query);
    }

    /**
     * @param  array<string, mixed>  $query
     */
    public static function viewUrl(ManagedEnvironment $environment, array $query = []): string
    {
        $workspace = self::workspaceFromScope($environment);

        if (! $workspace instanceof Workspace) {
            return url('/admin');
        }

        return self::withQuery(route('admin.workspace.environments.show', [
            'workspace' => self::workspaceRouteKey($workspace),
            'environment' => self::environmentRouteKey($environment),
        ]), $query);
    }

    /**
     * @param  array<string, mixed>  $filters
     */
    public static function requiredPermissionsUrl(ManagedEnvironment $environment, array $filters = []): string
    {
        return RequiredPermissionsLinks::requiredPermissions($environment, $filters);
    }

    /**
     * @param  array<string, mixed>  $query
     */
    public static function diagnosticsUrl(ManagedEnvironment $environment, array $query = []): string
    {
        return self::environmentChildUrl('admin.workspace.environments.diagnostics', $environment, $query);
    }

    /**
     * @param  array<string, mixed>  $query
     */
    public static function accessScopesUrl(ManagedEnvironment $environment, array $query = []): string
    {
        return self::environmentChildUrl('admin.workspace.environments.access-scopes', $environment, $query);
    }

    /**
     * @param  array<string, mixed>  $query
     */
    public static function baselineCompareUrl(ManagedEnvironment $environment, array $query = []): string
    {
        return BaselineCompareLanding::getUrl($query, panel: 'admin', tenant: $environment);
    }

    /**
     * @param  array<string, mixed>  $query
     */
    public static function providerConnectionsUrl(?ManagedEnvironment $environment = null, array $query = []): string
    {
        if ($environment instanceof ManagedEnvironment && ! array_key_exists('environment_id', $query)) {
            $query['environment_id'] = (int) $environment->getKey();
        }

        return ProviderConnectionResource::getUrl('index', $query, panel: 'admin');
    }

    /**
     * @param  array<string, mixed>  $query
     */
    public static function providerConnectionUrl(
        ProviderConnection|int $connection,
        string $page = 'view',
        ?ManagedEnvironment $environment = null,
        array $query = [],
    ): string {
        if ($environment instanceof ManagedEnvironment && ! array_key_exists('environment_id', $query)) {
            $query['environment_id'] = (int) $environment->getKey();
        }

        $query['record'] = $connection;

        return ProviderConnectionResource::getUrl($page, $query, panel: 'admin');
    }

    /**
     * @param  array<string, mixed>  $query
     */
    public static function operationsUrl(Workspace|ManagedEnvironment|null $scope = null, array $query = []): string
    {
        if ($scope instanceof ManagedEnvironment && ! array_key_exists('environment_id', $query)) {
            $query['environment_id'] = (int) $scope->getKey();
        }

        $workspace = self::workspaceFromScope($scope);

        if (! $workspace instanceof Workspace) {
            return url('/admin');
        }

        return self::withQuery(route('admin.operations.index', [
            'workspace' => self::workspaceRouteKey($workspace),
        ]), $query);
    }

    public static function workspaceRouteKey(Workspace $workspace): string
    {
        $slug = $workspace->getAttribute('slug');

        return is_string($slug) && $slug !== ''
            ? $slug
            : (string) $workspace->getKey();
    }

    public static function environmentRouteKey(ManagedEnvironment $environment): string
    {
        return (string) $environment->getRouteKey();
    }

    /**
     * @param  array<string, mixed>  $query
     */
    private static function environmentChildUrl(string $routeName, ManagedEnvironment $environment, array $query = []): string
    {
        $workspace = self::workspaceFromScope($environment);

        if (! $workspace instanceof Workspace) {
            return url('/admin');
        }

        return self::withQuery(route($routeName, [
            'workspace' => self::workspaceRouteKey($workspace),
            'environment' => self::environmentRouteKey($environment),
        ]), $query);
    }

    private static function workspaceFromScope(Workspace|ManagedEnvironment|null $scope = null): ?Workspace
    {
        if ($scope instanceof Workspace) {
            return $scope;
        }

        if ($scope instanceof ManagedEnvironment) {
            return $scope->workspace()->first();
        }

        return app(WorkspaceContext::class)->currentWorkspace(request());
    }

    /**
     * @param  array<string, mixed>  $query
     */
    private static function withQuery(string $url, array $query): string
    {
        $query = array_filter(
            $query,
            static fn (mixed $value): bool => $value !== null && $value !== '',
        );

        if ($query === []) {
            return $url;
        }

        $queryString = http_build_query($query);

        return $queryString !== '' ? "{$url}?{$queryString}" : $url;
    }
}
