<?php

namespace Kylin\Catering\Models;

use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\BelongsTo;

/**
 * 食品安全检查记录
 */
class InspectionRecord extends Model
{
    protected $table = 'catering_inspection_records';
    protected $fillable = [
        'supplier_id',
        'ingredient_name',
        'quantity',
        'unit',
        'production_date',
        'expiry_date',
        'batch_number',
        'inspection_result',
        'inspector',
        'remark',
        'retention_until',
    ];

    protected $casts = [
        'supplier_id' => 'integer',
        'quantity' => 'decimal:2',
        'production_date' => 'date',
        'expiry_date' => 'date',
        'retention_until' => 'date',
    ];

    public function supplier(): BelongsTo
    {
        return $this->belongsTo(Supplier::class);
    }

    protected static function booted(): void
    {
        static::creating(function (self $record) {
            // 保留期限：保质期满后6个月，无明确保质期则2年
            if ($record->expiry_date) {
                $record->retention_until = $record->expiry_date->addMonths(6);
            } else {
                $record->retention_until = now()->addYears(2);
            }
        });
    }
}
