<?php

namespace Kylin\Catering\Models;

use Illuminate\Database\Eloquent\Model;

/**
 * 食品留样记录
 */
class SampleRecord extends Model
{
    protected $table = 'catering_sample_records';
    protected $fillable = [
        'dish_name',
        'sample_time',
        'sample_amount',
        'storage_location',
        'sampler',
        'retention_until',
        'remark',
    ];

    protected $casts = [
        'sample_time' => 'datetime',
        'sample_amount' => 'decimal:2',
        'retention_until' => 'datetime',
    ];

    protected static function booted(): void
    {
        static::creating(function (self $record) {
            // 依据《餐饮服务食品安全操作规范》7.5，留样量不少于125克
            $minWeight = (int) config('kylin-catering.sample.min_weight', 125);
            if ((float) $record->sample_amount < $minWeight) {
                throw new \InvalidArgumentException("食品留样重量不得少于 {$minWeight} 克");
            }

            // 留样保留48小时
            $record->retention_until = $record->sample_time->addHours(48);
        });
    }

    public function isExpired(): bool
    {
        return $this->retention_until && now()->gt($this->retention_until);
    }
}
