<?php

namespace App\Models\Estimate;

use App\Traits\Auditable;
use App\Traits\BelongsToTenant;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\BelongsTo;
use Illuminate\Database\Eloquent\SoftDeletes;

class EstimateItem extends Model
{
    use Auditable, BelongsToTenant, HasFactory, SoftDeletes;

    protected $fillable = [
        'tenant_id',
        'estimate_id',
        'sequence',
        'item_name',
        'item_description',
        'parameters',
        'calculated_values',
        'unit_price',
        'quantity',
        'total_price',
        'bom_components',
        'notes',
        'created_by',
        'updated_by',
        'deleted_by',
    ];

    protected $casts = [
        'parameters' => 'array',
        'calculated_values' => 'array',
        'unit_price' => 'decimal:2',
        'quantity' => 'decimal:2',
        'total_price' => 'decimal:2',
        'bom_components' => 'array',
        'created_at' => 'datetime',
        'updated_at' => 'datetime',
        'deleted_at' => 'datetime',
    ];

    /**
     * 견적 관계
     */
    public function estimate(): BelongsTo
    {
        return $this->belongsTo(Estimate::class);
    }

    /**
     * 순번별 정렬
     */
    public function scopeOrdered($query)
    {
        return $query->orderBy('sequence');
    }

    /**
     * 총 금액 계산
     */
    public function calculateTotalPrice(): float
    {
        return $this->unit_price * $this->quantity;
    }

    /**
     * 저장 시 총 금액 자동 계산
     */
    protected static function boot()
    {
        parent::boot();

        static::saving(function ($item) {
            $item->total_price = $item->calculateTotalPrice();
        });
    }
}
