<?php

namespace App\Traits;

use Illuminate\Database\Eloquent\Builder;

trait HasOwnership
{
    /**
     * Boot the trait.
     */
    protected static function bootHasOwnership()
    {
        static::addGlobalScope('ownership', function (Builder $builder) {
            if (auth()->check()) {
                $user = auth()->user();
                $modelName = strtolower(class_basename(get_called_class()));

                // Map model name to permission module name if different
                $mapping = [
                    'financialtransaction' => 'transactions',
                    'financialtreasury' => 'treasuries',
                ];

                $module = $mapping[$modelName] ?? $modelName . 's';

                // If user doesn't have "full" access to this module, filter by user_id
                if (!$user->hasPermissionTo("full {$module}") && !$user->hasRole('admin')) {
                    $builder->where(function ($query) {
                        $query->where('user_id', auth()->id())
                            ->orWhereNull('user_id'); // Allow seeing public/unowned data
                    });
                }
            }
        });

        static::creating(function ($model) {
            if (auth()->check() && empty($model->user_id)) {
                $model->user_id = auth()->id();
            }
        });
    }
}
