<?php

namespace Modules\MedSurgery\Entities;

use Illuminate\Database\Eloquent\Model;
use Illuminate\Support\Facades\DB;

/**
 * A surgical case (SIFA P6-T4). Status transitions, the consent gate and the
 * count-discrepancy rule are enforced by Modules\MedSurgery\Services\SurgeryService.
 * Reuse links (patient_id, primary_surgeon_id, or_room_id, consent_id, …) are
 * plain integers resolved at the application layer — no cross-module FKs.
 */
class MedsxCase extends Model
{
    protected $table = 'medsx_cases';

    protected $guarded = ['id'];

    protected $casts = [
        'assistant_ids'  => 'array',
        'procedures'     => 'array',
        'specimens'      => 'array',
        'implants'       => 'array',
        'asa_class'      => 'integer',
        'scheduled_date' => 'date',
        'scheduled_start' => 'datetime',
        'scheduled_end'  => 'datetime',
        'actual_start'   => 'datetime',
        'actual_end'     => 'datetime',
    ];

    public const STATUSES = [
        'scheduled', 'pre_op', 'in_or', 'post_op', 'completed', 'cancelled', 'postponed',
    ];

    public const PRIORITIES = ['elective', 'urgent', 'emergency'];

    public const ANESTHESIA_TYPES = [
        'general', 'spinal', 'epidural', 'regional', 'local', 'sedation', 'combined',
    ];

    public const LATERALITIES = ['l', 'r', 'bilateral', 'na'];

    public const BLOOD_LOSS = ['minimal', 'moderate', 'significant', 'massive'];

    public function checklists()
    {
        return $this->hasMany(MedsxChecklist::class, 'case_id');
    }

    public function counts()
    {
        return $this->hasMany(MedsxCount::class, 'case_id');
    }

    public function scopeForBusiness($query, $businessId)
    {
        return $query->where('business_id', $businessId);
    }

    /** Allocate the next case reference: SX-{biz}-{0000001}. */
    public static function nextCaseNo(int $businessId): string
    {
        return DB::transaction(function () use ($businessId) {
            $last = static::where('business_id', $businessId)
                ->lockForUpdate()->orderByDesc('id')->value('case_no');
            $n = 1;
            if ($last && preg_match('/-(\d+)$/', $last, $m)) {
                $n = ((int) $m[1]) + 1;
            }

            return 'SX-' . $businessId . '-' . str_pad((string) $n, 7, '0', STR_PAD_LEFT);
        });
    }
}
