<?php

namespace App\Policies;

use App\Models\ProviderConnection;
use App\Models\Tenant;
use App\Models\User;
use Illuminate\Auth\Access\HandlesAuthorization;
use Illuminate\Auth\Access\Response;
use Illuminate\Support\Facades\Gate;

class ProviderConnectionPolicy
{
    use HandlesAuthorization;

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

        return Gate::forUser($user)->allows('provider.view', $tenant);
    }

    public function view(User $user, ProviderConnection $connection): Response|bool
    {
        $tenant = Tenant::current();

        if (! Gate::forUser($user)->allows('provider.view', $tenant)) {
            return false;
        }

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

        return true;
    }

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

        return Gate::forUser($user)->allows('provider.manage', $tenant);
    }

    public function update(User $user, ProviderConnection $connection): Response|bool
    {
        $tenant = Tenant::current();

        if (! Gate::forUser($user)->allows('provider.view', $tenant)) {
            return false;
        }

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

        return true;
    }

    public function delete(User $user, ProviderConnection $connection): Response|bool
    {
        $tenant = Tenant::current();

        if (! Gate::forUser($user)->allows('provider.manage', $tenant)) {
            return false;
        }

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

        return false;
    }
}
