<?php

namespace App\Models\Items;

use App\Models\Category;
use App\Traits\BelongsToTenant;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\SoftDeletes;

class Item extends Model
{
    use BelongsToTenant, SoftDeletes;

    protected $table = 'items';

    protected $fillable = [
        'tenant_id', 'item_type', 'item_category', 'code', 'name', 'unit',
        'category_id', 'bom', 'attributes', 'attributes_archive', 'options',
        'description', 'is_active', 'created_by', 'updated_by',
    ];

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

    // 유형 상수
    const TYPE_FG = 'FG';  // 완제품

    const TYPE_PT = 'PT';  // 부품

    const TYPE_SM = 'SM';  // 부자재

    const TYPE_RM = 'RM';  // 원자재

    const TYPE_CS = 'CS';  // 소모품

    const PRODUCT_TYPES = ['FG', 'PT'];

    const MATERIAL_TYPES = ['SM', 'RM', 'CS'];

    // ── 관계 ──

    public function details()
    {
        return $this->hasOne(ItemDetail::class, 'item_id');
    }

    public function category()
    {
        return $this->belongsTo(Category::class, 'category_id');
    }

    /**
     * 파일 (document_id/document_type 기반)
     * document_id = items.id, document_type = '1' (ITEM_GROUP_ID)
     */
    public function files()
    {
        return $this->hasMany(\App\Models\Commons\File::class, 'document_id')
            ->where('document_type', '1');
    }

    // ── 스코프 ──

    public function scopeType($query, string $type)
    {
        return $query->where('items.item_type', strtoupper($type));
    }

    public function scopeActive($query)
    {
        return $query->where('is_active', true);
    }

    public function scopeSearch($query, ?string $search)
    {
        if (! $search) {
            return $query;
        }

        return $query->where(function ($q) use ($search) {
            $q->where('code', 'like', "%{$search}%")
                ->orWhere('name', 'like', "%{$search}%");
        });
    }

    // ── 헬퍼 ──

    public function isProduct(): bool
    {
        return in_array($this->item_type, self::PRODUCT_TYPES);
    }

    public function isMaterial(): bool
    {
        return in_array($this->item_type, self::MATERIAL_TYPES);
    }

    public function getBomChildIds(): array
    {
        return collect($this->bom ?? [])->pluck('child_item_id')->filter()->toArray();
    }
}
