<?php

namespace App\Policies\Concerns;

use App\Models\User;
use Illuminate\Database\Eloquent\Model;

trait AuthorizesOwnershipOrShare
{
    public function viewAny(User $user): bool
    {
        return true;
    }

    public function create(User $user): bool
    {
        return $user->suspended_at === null;
    }

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

    public function update(User $user, Model $model): bool
    {
        if ($user->isSuperAdmin()) {
            return true;
        }

        if ((int) $model->user_id === $user->id) {
            return true;
        }

        return $model->shares()
            ->where('shared_with_user_id', $user->id)
            ->where('permission', 'edit')
            ->exists();
    }

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

    public function share(User $user, Model $model): bool
    {
        return $this->isOwnerOrAdmin($user, $model);
    }

    protected function canAccess(User $user, Model $model): bool
    {
        if ($this->isOwnerOrAdmin($user, $model)) {
            return true;
        }

        return $model->shares()->where('shared_with_user_id', $user->id)->exists();
    }

    protected function isOwnerOrAdmin(User $user, Model $model): bool
    {
        return $user->isSuperAdmin() || (int) $model->user_id === $user->id;
    }
}
