<?php

declare(strict_types=1);

namespace App\Policies;

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

class ReviewPackPolicy
{
    use HandlesAuthorization;

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

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

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

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

        return $resolver->can($user, $tenant, Capabilities::REVIEW_PACK_VIEW);
    }

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

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

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

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

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

        return $resolver->can($user, $tenant, Capabilities::REVIEW_PACK_VIEW);
    }

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

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

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

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

        return $resolver->can($user, $tenant, Capabilities::REVIEW_PACK_MANAGE);
    }

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

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

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

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

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

        return $resolver->can($user, $tenant, Capabilities::REVIEW_PACK_MANAGE);
    }
}
