<?php

declare(strict_types=1);

namespace App\Policies;

use App\Models\EvidenceSnapshot;
use App\Models\ManagedEnvironment;
use App\Models\User;
use App\Services\Auth\CapabilityResolver;
use App\Support\Auth\Capabilities;
use Illuminate\Auth\Access\HandlesAuthorization;
use Illuminate\Auth\Access\Response;

class EvidenceSnapshotPolicy
{
    use HandlesAuthorization;

    public function viewAny(User $user): bool
    {
        $tenant = ManagedEnvironment::current();

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

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

    public function view(User $user, EvidenceSnapshot $snapshot): Response|bool
    {
        $tenant = ManagedEnvironment::current();

        if (! $tenant instanceof ManagedEnvironment || ! $user->canAccessTenant($tenant)) {
            return Response::denyAsNotFound();
        }

        if ((int) $snapshot->managed_environment_id !== (int) $tenant->getKey()) {
            return Response::denyAsNotFound();
        }

        return app(CapabilityResolver::class)->can($user, $tenant, Capabilities::EVIDENCE_VIEW)
            ? true
            : Response::deny();
    }

    public function create(User $user): bool
    {
        $tenant = ManagedEnvironment::current();

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

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

    public function delete(User $user, EvidenceSnapshot $snapshot): Response|bool
    {
        $tenant = ManagedEnvironment::current();

        if (! $tenant instanceof ManagedEnvironment || ! $user->canAccessTenant($tenant)) {
            return Response::denyAsNotFound();
        }

        if ((int) $snapshot->managed_environment_id !== (int) $tenant->getKey()) {
            return Response::denyAsNotFound();
        }

        return app(CapabilityResolver::class)->can($user, $tenant, Capabilities::EVIDENCE_MANAGE)
            ? true
            : Response::deny();
    }
}
