<?php

namespace App\Traits;

use App\Helpers\TenantHelper;
use Illuminate\Database\Eloquent\Builder;

trait HasTenantFilter
{
    public static function getEloquentQuery(): Builder
    {
        return parent::getEloquentQuery()
            ->when(TenantHelper::hasTenantSelected(), function (Builder $query) {
                return TenantHelper::applyTenantFilter($query);
            }, function (Builder $query) {
                // 테넌트가 선택되지 않으면 빈 결과
                return $query->whereRaw('1 = 0');
            });
    }

    protected function mutateFormDataBeforeCreate(array $data): array
    {
        return TenantHelper::setTenantId($data);
    }

    protected function mutateFormDataBeforeSave(array $data): array
    {
        return TenantHelper::setTenantId($data);
    }
}
