<?php

declare(strict_types=1);

namespace App\Policies;

use App\Models\ReviewPack;
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 ReviewPackPolicy
{
    use HandlesAuthorization;

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

        if (! $tenant instanceof ManagedEnvironment) {
            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): Response|bool
    {
        $tenant = ManagedEnvironment::current();

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

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

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

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

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

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

        if (! $tenant instanceof ManagedEnvironment) {
            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): Response|bool
    {
        $tenant = ManagedEnvironment::current();

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

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

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

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

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