<?php

namespace App\Policies\Concerns;

use App\Enums\UserRole;
use App\Models\User;

trait AuthorizesTenantModels
{
    public function before(User $user): ?bool
    {
        return $user->isSuperAdmin() ? true : null;
    }

    public function viewAny(User $user): bool
    {
        return $user->hasRole(UserRole::BusinessOwner) || $user->hasRole(UserRole::Staff);
    }

    public function view(User $user, mixed $model): bool
    {
        return $this->belongsToAccessibleBusiness($user, $model);
    }

    public function create(User $user): bool
    {
        return $user->hasRole(UserRole::BusinessOwner);
    }

    public function update(User $user, mixed $model): bool
    {
        return $user->hasRole(UserRole::BusinessOwner)
            && $this->belongsToAccessibleBusiness($user, $model);
    }

    public function delete(User $user, mixed $model): bool
    {
        return $user->hasRole(UserRole::BusinessOwner)
            && $this->belongsToAccessibleBusiness($user, $model);
    }

    public function restore(User $user, mixed $model): bool
    {
        return $this->delete($user, $model);
    }

    public function forceDelete(User $user, mixed $model): bool
    {
        return $this->delete($user, $model);
    }

    protected function belongsToAccessibleBusiness(User $user, mixed $model): bool
    {
        $businessId = data_get($model, 'business_id');

        return $businessId && $user->canAccessBusiness((int) $businessId);
    }
}
