<?php

namespace App\Traits;

use App\Models\Store;
use Illuminate\Database\Eloquent\Builder;
use Illuminate\Database\Eloquent\Relations\BelongsTo;

/**
 * 门店隔离 Trait
 * 使用方法：在 Model 中 use BelongsToStore;
 * 自动 Scope 过滤当前门店数据
 */
trait BelongsToStore
{
    public static function bootBelongsToStore(): void
    {
        // 查询自动过滤门店
        static::addGlobalScope('store', function (Builder $builder) {
            if ($storeId = self::getCurrentStoreId()) {
                $builder->where($builder->getModel()->getTable() . '.store_id', $storeId);
            }
        });

        // 创建时自动填入 store_id
        static::creating(function ($model) {
            if (empty($model->store_id)) {
                $model->store_id = self::getCurrentStoreId();
            }
        });
    }

    public function store(): BelongsTo
    {
        return $this->belongsTo(Store::class);
    }

    private static function getCurrentStoreId(): ?int
    {
        $user = auth()->user();
        if ($user && $user->is_super && request()->header('X-Store-Id')) {
            return (int) request()->header('X-Store-Id');
        }
        return $user?->store_id;
    }
}
