<?php

namespace App\Policies;

use App\Models\Finding;
use App\Models\ManagedEnvironment;
use App\Models\User;
use App\Services\Auth\CapabilityResolver;
use App\Support\Auth\Capabilities;
use App\Support\OperateHub\OperateHubShell;
use Filament\Facades\Filament;
use Illuminate\Auth\Access\HandlesAuthorization;
use Illuminate\Auth\Access\Response;

class FindingPolicy
{
    use HandlesAuthorization;

    public function viewAny(User $user): bool
    {
        $tenant = $this->resolvedTenant();

        if (! $tenant instanceof ManagedEnvironment) {
            return false;
        }

        if (! $user->canAccessTenant($tenant)) {
            return false;
        }

        return app(CapabilityResolver::class)->can($user, $tenant, Capabilities::TENANT_FINDINGS_VIEW);
    }

    public function view(User $user, Finding $finding): Response|bool
    {
        $tenant = $this->authorizedTenantOrNull($user, $finding);

        if (! $tenant instanceof ManagedEnvironment) {
            return Response::denyAsNotFound();
        }

        return app(CapabilityResolver::class)->can($user, $tenant, Capabilities::TENANT_FINDINGS_VIEW);
    }

    public function update(User $user, Finding $finding): Response|bool
    {
        return $this->triage($user, $finding);
    }

    public function triage(User $user, Finding $finding): Response|bool
    {
        return $this->canMutateWithCapability($user, $finding, Capabilities::TENANT_FINDINGS_TRIAGE);
    }

    public function assign(User $user, Finding $finding): Response|bool
    {
        return $this->canMutateWithCapability($user, $finding, Capabilities::TENANT_FINDINGS_ASSIGN);
    }

    public function resolve(User $user, Finding $finding): Response|bool
    {
        return $this->canMutateWithCapability($user, $finding, Capabilities::TENANT_FINDINGS_RESOLVE);
    }

    public function close(User $user, Finding $finding): Response|bool
    {
        return $this->canMutateWithCapability($user, $finding, Capabilities::TENANT_FINDINGS_CLOSE);
    }

    public function riskAccept(User $user, Finding $finding): Response|bool
    {
        return $this->canMutateWithCapability($user, $finding, Capabilities::TENANT_FINDINGS_RISK_ACCEPT);
    }

    public function reopen(User $user, Finding $finding): Response|bool
    {
        return $this->triage($user, $finding);
    }

    private function canMutateWithCapability(User $user, Finding $finding, string $capability): Response|bool
    {
        return $this->canMutateWithAnyCapability($user, $finding, [$capability]);
    }

    /**
     * @param  array<int, string>  $capabilities
     */
    private function canMutateWithAnyCapability(User $user, Finding $finding, array $capabilities): Response|bool
    {
        $tenant = $this->authorizedTenantOrNull($user, $finding);

        if (! $tenant instanceof ManagedEnvironment) {
            return Response::denyAsNotFound();
        }

        /** @var CapabilityResolver $resolver */
        $resolver = app(CapabilityResolver::class);

        foreach ($capabilities as $capability) {
            if ($resolver->can($user, $tenant, $capability)) {
                return true;
            }
        }

        return Response::deny();
    }

    private function authorizedTenantOrNull(User $user, Finding $finding): ?ManagedEnvironment
    {
        $tenant = $this->resolvedTenant();

        if (! $tenant instanceof ManagedEnvironment) {
            return null;
        }

        if (! $user->canAccessTenant($tenant)) {
            return null;
        }

        if ((int) $finding->managed_environment_id !== (int) $tenant->getKey()) {
            return null;
        }

        if ((int) $finding->workspace_id !== (int) $tenant->workspace_id) {
            return null;
        }

        return $tenant;
    }

    private function resolvedTenant(): ?ManagedEnvironment
    {
        if (Filament::getCurrentPanel()?->getId() === 'admin') {
            $tenant = app(OperateHubShell::class)->tenantOwnedPanelContext(request());

            return $tenant instanceof ManagedEnvironment ? $tenant : null;
        }

        $tenant = ManagedEnvironment::current();

        return $tenant instanceof ManagedEnvironment ? $tenant : null;
    }
}
