<?php

namespace Modules\MedSurgery\Entities;

use Illuminate\Database\Eloquent\Model;

/**
 * A surgical item count (sponge / instrument / needle) for a case. `discrepancy`
 * is recomputed on every save from the boot hook: true when a recorded (non-null)
 * close_count or final_count differs from pre_count. A case cannot reach
 * `completed` while any count is in discrepancy and unacknowledged.
 */
class MedsxCount extends Model
{
    protected $table = 'medsx_counts';

    protected $guarded = ['id'];

    protected $casts = [
        'pre_count'   => 'integer',
        'close_count' => 'integer',
        'final_count' => 'integer',
        'discrepancy' => 'boolean',
        'counted_at'  => 'datetime',
    ];

    public const COUNT_TYPES = ['sponge', 'instrument', 'needle'];

    protected static function booted(): void
    {
        // Compute discrepancy on save (spec §16 sponge_count discrepancy_alert).
        static::saving(function (MedsxCount $count) {
            $count->discrepancy = self::computeDiscrepancy($count);
        });
    }

    /** A non-null close/final count that differs from pre_count is a discrepancy. */
    public static function computeDiscrepancy(MedsxCount $count): bool
    {
        $pre = (int) $count->pre_count;

        if ($count->close_count !== null && (int) $count->close_count !== $pre) {
            return true;
        }
        if ($count->final_count !== null && (int) $count->final_count !== $pre) {
            return true;
        }

        return false;
    }

    public function surgicalCase()
    {
        return $this->belongsTo(MedsxCase::class, 'case_id');
    }
}
