<?php

namespace App\Models\Machine;

use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;

class MachineLog extends Model
{
    use HasFactory;

    const UPDATED_AT = null;

    protected $fillable = [
        'company_id',
        'machine_id',
        'level',
        'type',
        'message',
        'context',
    ];

    protected $casts = [
        'context' => 'array',
    ];

    protected $appends = [
        'translated_message',
    ];

    /**
     * 動態重組翻譯後的訊息
     */
    public function getTranslatedMessageAttribute(): string
    {
        $context = $this->context;

        // 若 context 中已有翻譯標籤 (B013 封裝)，則進行動態重組
        if (isset($context['translated_label'])) {
            $label = __($context['translated_label']);
            $tid = $context['tid'] ?? null;
            $code = $context['raw_code'] ?? '0000';

            if ($tid) {
                return __('Slot') . " {$tid}: {$label} (Code: {$code})";
            }
            return "{$label} (Code: {$code})";
        }

        // 預設退回原始 message (支援歷史資料的翻譯判定與佔位符替換)
        return __($this->message, $context ?? []);
    }

    public function machine()
    {
        return $this->belongsTo(Machine::class);
    }
}
