<?php

namespace App\Support\Links;

use App\Models\ProviderConnection;
use App\Models\ManagedEnvironment;
use App\Models\Workspace;
use App\Services\Providers\AdminConsentUrlFactory;

final class RequiredPermissionsLinks
{
    private const ADMIN_CONSENT_GUIDE_URL = 'https://learn.microsoft.com/en-us/entra/identity/enterprise-apps/grant-admin-consent';

    /**
     * @param  array<string, mixed>  $filters
     */
    public static function requiredPermissions(ManagedEnvironment $tenant, array $filters = []): string
    {
        $workspace = $tenant->workspace()->first();

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

        $base = url(sprintf(
            '/admin/workspaces/%s/environments/%s/required-permissions',
            urlencode((string) ($workspace->slug ?? $workspace->getKey())),
            urlencode((string) $tenant->getRouteKey()),
        ));

        if ($filters === []) {
            return $base;
        }

        $query = http_build_query($filters);

        return $query !== '' ? "{$base}?{$query}" : $base;
    }

    public static function adminConsentUrl(ManagedEnvironment $tenant): ?string
    {
        $connection = ProviderConnection::query()
            ->where('managed_environment_id', (int) $tenant->getKey())
            ->where('provider', 'microsoft')
            ->orderByDesc('is_default')
            ->orderBy('id')
            ->first();

        if (! $connection instanceof ProviderConnection) {
            return null;
        }

        try {
            return app(AdminConsentUrlFactory::class)->make($connection, sprintf('tenantpilot|%s', $tenant->id));
        } catch (\Throwable) {
            return null;
        }
    }

    public static function adminConsentGuideUrl(): string
    {
        return self::ADMIN_CONSENT_GUIDE_URL;
    }

    public static function adminConsentPrimaryUrl(ManagedEnvironment $tenant): string
    {
        return self::adminConsentUrl($tenant) ?? self::adminConsentGuideUrl();
    }
}
