<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\BelongsTo;
use Illuminate\Database\Eloquent\Relations\HasMany;
use Spatie\Activitylog\Traits\LogsActivity;
use Spatie\Activitylog\LogOptions;

class ManufacturingBOMStep extends Model
{
    use LogsActivity;

    protected $table = 'manufacturing_bom_steps';

    protected $fillable = [
        'manufacturing_bom_id',
        'step_name',
        'instruction',
        'sequence_order',
    ];

    protected $casts = [
        'manufacturing_bom_id' => 'integer',
        'sequence_order' => 'integer',
    ];

    // Relationships
    public function manufacturingBom(): BelongsTo
    {
        return $this->belongsTo(ManufacturingBOM::class, 'manufacturing_bom_id');
    }

    public function ingredients(): HasMany
    {
        return $this->hasMany(ManufacturingBOMIngredient::class, 'manufacturing_bom_step_id');
    }

    // Scopes
    public function scopeForBom($query, $bomId)
    {
        return $query->where('manufacturing_bom_id', $bomId);
    }

    public function scopeOrdered($query)
    {
        return $query->orderBy('sequence_order');
    }

    // Helper methods
    public function getTotalIngredientsAttribute()
    {
        return $this->ingredients()->count();
    }

    public function getActivitylogOptions(): LogOptions
    {
        return LogOptions::defaults()
            ->useLogName('manufacturing_bom_step')
            ->logFillable()
            ->logOnlyDirty()
            ->dontSubmitEmptyLogs();
    }
}
