<?php

declare(strict_types=1);

namespace App\Support\Navigation;

use App\Filament\Pages\BaselineCompareMatrix;
use App\Filament\Resources\ManagedEnvironmentResource\Pages\ListManagedEnvironments;
use App\Models\BaselineProfile;
use App\Models\ManagedEnvironment;
use Filament\Facades\Filament;
use Illuminate\Http\Request;

final readonly class CanonicalNavigationContext
{
    /**
     * @param  array<string, mixed>  $filterPayload
     */
    public function __construct(
        public string $sourceSurface,
        public string $canonicalRouteName,
        public ?int $tenantId = null,
        public ?string $familyKey = null,
        public ?string $backLinkLabel = null,
        public ?string $backLinkUrl = null,
        public array $filterPayload = [],
    ) {}

    /**
     * @param  array<string, mixed>|null  $payload
     */
    public static function fromPayload(?array $payload): ?self
    {
        if (! is_array($payload)) {
            return null;
        }

        return self::fromRequest(new Request(query: ['nav' => $payload]));
    }

    public static function fromRequest(Request $request): ?self
    {
        $payload = $request->query('nav');

        if (! is_array($payload)) {
            return null;
        }

        $sourceSurface = $payload['source_surface'] ?? null;
        $canonicalRouteName = $payload['canonical_route_name'] ?? null;

        if (! is_string($sourceSurface) || $sourceSurface === '' || ! is_string($canonicalRouteName) || $canonicalRouteName === '') {
            return null;
        }

        $tenantId = $payload['environment_id'] ?? null;

        return new self(
            sourceSurface: $sourceSurface,
            canonicalRouteName: $canonicalRouteName,
            tenantId: is_numeric($tenantId) ? (int) $tenantId : null,
            familyKey: is_string($payload['family_key'] ?? null) && (string) $payload['family_key'] !== ''
                ? (string) $payload['family_key']
                : null,
            backLinkLabel: is_string($payload['back_label'] ?? null) ? (string) $payload['back_label'] : null,
            backLinkUrl: is_string($payload['back_url'] ?? null) ? (string) $payload['back_url'] : null,
            filterPayload: [],
        );
    }

    public static function forGovernanceInbox(
        string $canonicalRouteName,
        ?int $tenantId,
        ?string $familyKey,
        string $backLinkUrl,
    ): self {
        return new self(
            sourceSurface: 'governance.inbox',
            canonicalRouteName: $canonicalRouteName,
            tenantId: $tenantId,
            familyKey: $familyKey,
            backLinkLabel: 'Back to governance inbox',
            backLinkUrl: $backLinkUrl,
        );
    }

    public static function forDecisionRegister(
        string $canonicalRouteName,
        ?int $tenantId,
        string $backLinkUrl,
    ): self {
        return new self(
            sourceSurface: 'governance.decision_register',
            canonicalRouteName: $canonicalRouteName,
            tenantId: $tenantId,
            backLinkLabel: 'Back to decision register',
            backLinkUrl: $backLinkUrl,
        );
    }

    public static function forTenantRegistry(string $backLinkUrl, ?int $tenantId = null): self
    {
        return new self(
            sourceSurface: 'tenant_registry',
            canonicalRouteName: ListManagedEnvironments::getRouteName(Filament::getPanel('admin')),
            tenantId: $tenantId,
            backLinkLabel: __('localization.shell.back_to_environment_registry'),
            backLinkUrl: $backLinkUrl,
        );
    }

    /**
     * @return array<string, mixed>
     */
    public function toQuery(): array
    {
        $query = $this->filterPayload;
        $query['nav'] = $this->navPayload();

        return $query;
    }

    /**
     * @return array{nav: array<string, mixed>}
     */
    public function navQuery(): array
    {
        return ['nav' => $this->navPayload()];
    }

    /**
     * @param  array<string, mixed>  $filters
     */
    public static function forBaselineCompareMatrix(
        BaselineProfile $profile,
        array $filters = [],
        ?ManagedEnvironment $tenant = null,
        ?string $subjectKey = null,
    ): self {
        $parameters = array_filter([
            'record' => $profile,
            ...$filters,
        ], static fn (mixed $value): bool => $value !== null && $value !== [] && $value !== '');

        return new self(
            sourceSurface: 'baseline_compare_matrix',
            canonicalRouteName: BaselineCompareMatrix::getRouteName(),
            tenantId: $tenant?->getKey(),
            backLinkLabel: 'Back to compare matrix',
            backLinkUrl: BaselineCompareMatrix::getUrl($parameters, panel: 'admin'),
            filterPayload: array_filter([
                'baseline_profile_id' => (int) $profile->getKey(),
                'subject_key' => $subjectKey,
            ], static fn (mixed $value): bool => $value !== null && $value !== ''),
        );
    }

    /**
     * @return array<string, mixed>
     */
    private function navPayload(): array
    {
        return array_filter([
            'source_surface' => $this->sourceSurface,
            'canonical_route_name' => $this->canonicalRouteName,
            'environment_id' => $this->tenantId,
            'family_key' => $this->familyKey,
            'back_label' => $this->backLinkLabel,
            'back_url' => $this->backLinkUrl,
        ], static fn (mixed $value): bool => $value !== null && $value !== '');
    }
}
