<?php

namespace App\Support\Links;

use App\Models\ProviderConnection;
use App\Models\Tenant;
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(Tenant $tenant, array $filters = []): string
    {
        $base = sprintf('/admin/tenants/%s/required-permissions', urlencode((string) $tenant->external_id));

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

        $query = http_build_query($filters);

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

    public static function adminConsentUrl(Tenant $tenant): ?string
    {
        $connection = ProviderConnection::query()
            ->where('tenant_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(Tenant $tenant): string
    {
        return self::adminConsentUrl($tenant) ?? self::adminConsentGuideUrl();
    }
}
