<?php

declare(strict_types=1);

namespace App\Support\References\Resolvers;

use App\Filament\Resources\PolicyVersionResource;
use App\Models\PolicyVersion;
use App\Models\ManagedEnvironment;
use App\Models\User;
use App\Services\Auth\CapabilityResolver;
use App\Support\Auth\Capabilities;
use App\Support\References\ReferenceClass;
use App\Support\References\ReferenceDescriptor;
use App\Support\References\ReferenceLinkTarget;
use App\Support\References\ResolvedReference;

final class PolicyVersionReferenceResolver extends BaseReferenceResolver
{
    public function __construct(
        \App\Support\References\ReferenceTypeLabelCatalog $typeLabels,
        private readonly CapabilityResolver $capabilityResolver,
    ) {
        parent::__construct($typeLabels);
    }

    public function referenceClass(): ReferenceClass
    {
        return ReferenceClass::PolicyVersion;
    }

    public function resolve(ReferenceDescriptor $descriptor): ResolvedReference
    {
        $policyVersionId = $this->linkedModelId($descriptor);
        $tenantId = $descriptor->tenantId;

        if ($policyVersionId === null || $tenantId === null || $tenantId <= 0) {
            return $this->unresolved($descriptor);
        }

        $version = PolicyVersion::query()
            ->with(['policy', 'tenant'])
            ->whereKey($policyVersionId)
            ->where('managed_environment_id', $tenantId)
            ->first();

        if (! $version instanceof PolicyVersion) {
            return $this->missing($descriptor);
        }

        if (! $this->canOpenPolicyVersion($version)) {
            return $this->inaccessible($descriptor);
        }

        $policyName = $version->policy?->display_name;
        $secondary = __('localization.policy.versions.reference_version_number', ['version' => (string) $version->version_number]);

        if (is_string($version->capture_purpose?->value) && $version->capture_purpose->value !== '') {
            $secondary .= ' · '.str_replace('_', ' ', $version->capture_purpose->value);
        }

        return $this->resolved(
            descriptor: $descriptor,
            primaryLabel: is_string($policyName) && trim($policyName) !== '' ? $policyName : __('localization.policy.versions.related_entry_policy_version'),
            secondaryLabel: $secondary,
            linkTarget: new ReferenceLinkTarget(
                targetKind: ReferenceClass::PolicyVersion->value,
                url: PolicyVersionResource::getUrl('view', ['record' => $version], tenant: $version->tenant),
                actionLabel: __('localization.policy.versions.related_action_view_policy_version'),
                contextBadge: 'ManagedEnvironment',
            ),
        );
    }

    private function canOpenPolicyVersion(PolicyVersion $version): bool
    {
        $tenant = $version->tenant;

        if (! $tenant instanceof ManagedEnvironment || ! $this->canOpenTenantRecord($tenant, Capabilities::TENANT_VIEW)) {
            return false;
        }

        if (in_array((string) $version->capture_purpose?->value, ['baseline_capture', 'baseline_compare'], true)) {
            $user = auth()->user();

            return $user instanceof User
                && $this->capabilityResolver->isMember($user, $tenant)
                && $this->capabilityResolver->can($user, $tenant, Capabilities::TENANT_SYNC);
        }

        return true;
    }

    private function canOpenTenantRecord(?ManagedEnvironment $tenant, string $capability): bool
    {
        $user = auth()->user();

        return $tenant instanceof ManagedEnvironment
            && $user instanceof User
            && $this->capabilityResolver->isMember($user, $tenant)
            && $this->capabilityResolver->can($user, $tenant, $capability);
    }
}
