<?php

namespace App\Models\Products;

use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\SoftDeletes;

class CommonCode extends Model
{
    use SoftDeletes;

    protected $table = 'common_codes';

    protected $fillable = [
        'tenant_id',
        'code_group',
        'code',
        'name',
        'parent_id',
        'attributes',
        'description',
        'is_active',
        'sort_order',
    ];

    protected $casts = [
        'attributes' => 'array',
        'is_active' => 'boolean',
    ];

    /**
     * 테넌트별 품목유형 목록 조회 (tenant_id 또는 글로벌)
     *
     * @return array<string, string> [code => name]
     */
    public static function getItemTypes(int $tenantId): array
    {
        return static::query()
            ->where(function ($query) use ($tenantId) {
                $query->where('tenant_id', $tenantId)
                    ->orWhereNull('tenant_id');
            })
            ->where('code_group', 'item_type')
            ->where('is_active', true)
            ->orderBy('sort_order')
            ->pluck('name', 'code')
            ->toArray();
    }
}
