<?php

declare(strict_types=1);

namespace App\Support\References\Resolvers;

use App\Filament\Resources\PolicyResource;
use App\Models\Policy;
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 PolicyReferenceResolver extends BaseReferenceResolver
{
    public function __construct(
        \App\Support\References\ReferenceTypeLabelCatalog $typeLabels,
        private readonly CapabilityResolver $capabilityResolver,
    ) {
        parent::__construct($typeLabels);
    }

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

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

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

        $policy = Policy::query()
            ->with('tenant')
            ->whereKey($policyId)
            ->where('managed_environment_id', $tenantId)
            ->first();

        if (! $policy instanceof Policy) {
            return $this->missing($descriptor);
        }

        if (! $this->canOpenTenantRecord($policy->tenant, Capabilities::TENANT_VIEW)) {
            return $this->inaccessible($descriptor);
        }

        return $this->resolved(
            descriptor: $descriptor,
            primaryLabel: (string) ($policy->display_name ?: __('localization.policy.versions.related_entry_policy')),
            secondaryLabel: __('localization.policy.versions.reference_policy_number', ['id' => $policy->getKey()]),
            linkTarget: new ReferenceLinkTarget(
                targetKind: ReferenceClass::Policy->value,
                url: PolicyResource::getUrl('view', ['record' => $policy], tenant: $policy->tenant),
                actionLabel: __('localization.policy.versions.related_action_view_policy'),
                contextBadge: 'ManagedEnvironment',
            ),
        );
    }

    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);
    }
}
