<?php

declare(strict_types=1);

namespace App\Policies;

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

class EvidenceSnapshotPolicy
{
    use HandlesAuthorization;

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

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

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

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

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

        if ((int) $snapshot->tenant_id !== (int) $tenant->getKey()) {
            return false;
        }

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

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

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

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

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

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

        if ((int) $snapshot->tenant_id !== (int) $tenant->getKey()) {
            return false;
        }

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