<?php

namespace App\Policies;

use App\Models\BackupSchedule;
use App\Models\Tenant;
use App\Models\User;
use App\Support\Auth\Capabilities;
use Illuminate\Auth\Access\HandlesAuthorization;
use Illuminate\Support\Facades\Gate;

class BackupSchedulePolicy
{
    use HandlesAuthorization;

    protected function isTenantMember(User $user, ?Tenant $tenant = null): bool
    {
        $tenant ??= Tenant::current();

        return $tenant instanceof Tenant
            && Gate::forUser($user)->allows(Capabilities::TENANT_VIEW, $tenant);
    }

    public function viewAny(User $user): bool
    {
        return $this->isTenantMember($user);
    }

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

        if (! $this->isTenantMember($user, $tenant)) {
            return false;
        }

        return (int) $schedule->tenant_id === (int) $tenant->getKey();
    }

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

        return $tenant instanceof Tenant
            && Gate::forUser($user)->allows(Capabilities::TENANT_BACKUP_SCHEDULES_MANAGE, $tenant);
    }

    public function update(User $user, BackupSchedule $schedule): bool
    {
        $tenant = Tenant::current();

        return $tenant instanceof Tenant
            && (int) $schedule->tenant_id === (int) $tenant->getKey()
            && Gate::forUser($user)->allows(Capabilities::TENANT_BACKUP_SCHEDULES_MANAGE, $tenant);
    }

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

        return $tenant instanceof Tenant
            && (int) $schedule->tenant_id === (int) $tenant->getKey()
            && Gate::forUser($user)->allows(Capabilities::TENANT_BACKUP_SCHEDULES_MANAGE, $tenant);
    }

    public function restore(User $user, BackupSchedule $schedule): bool
    {
        $tenant = Tenant::current();

        return $tenant instanceof Tenant
            && (int) $schedule->tenant_id === (int) $tenant->getKey()
            && Gate::forUser($user)->allows(Capabilities::TENANT_BACKUP_SCHEDULES_MANAGE, $tenant);
    }

    public function forceDelete(User $user, BackupSchedule $schedule): bool
    {
        $tenant = Tenant::current();

        return $tenant instanceof Tenant
            && (int) $schedule->tenant_id === (int) $tenant->getKey()
            && Gate::forUser($user)->allows(Capabilities::TENANT_DELETE, $tenant);
    }
}
