<?php

namespace Modules\MedEmergency\Http\Controllers;

use Illuminate\Http\Request;
use Modules\MedEmergency\Entities\MderVisit;
use Modules\MedEmergency\Entities\MderVisitEvent;
use Modules\MedEmergency\Services\WardHandoffService;

/**
 * ER disposition (SIFA P6-T3). Closes a visit with an outcome. An `admitted`
 * disposition hands off to MedWard when available (creates a medward_admissions
 * row + deep-link, leaving the visit at admitted_awaiting_bed); otherwise — and
 * for every other disposition — the outcome is simply recorded and the visit
 * leaves the board (done). Guarded by mder.disposition.
 */
class DispositionController extends MedEmergencyBaseController
{
    public function store(Request $request, $id, WardHandoffService $ward)
    {
        $this->guard('mder.disposition');

        $data = $this->validate($request, [
            'disposition'      => 'required|string|in:' . implode(',', MderVisit::DISPOSITIONS),
            'disposition_note' => 'nullable|string|max:2000',
        ]);

        $visit = MderVisit::forBusiness($this->businessId())->findOrFail($id);

        if ($visit->isClosed()) {
            return $this->fail(__('medemergency::lang.visit_closed'));
        }

        $visit->disposition      = $data['disposition'];
        $visit->disposition_at   = now();
        $visit->disposition_note = $data['disposition_note'] ?? null;

        $handoff = null;

        if ($data['disposition'] === 'admitted') {
            // Fail-soft admit hand-off to MedWard.
            $handoff = $ward->admit($visit);

            if ($handoff['ok']) {
                $visit->medward_admission_id = $handoff['admission_id'];
                // Board keeps the patient boarding until a bed is assigned in MedWard.
                $visit->board_status = 'admitted_awaiting_bed';
            } else {
                // MedWard absent/unusable — the disposition is recorded only and the
                // visit still boards until an inpatient bed frees up.
                $visit->board_status = 'admitted_awaiting_bed';
            }
        } else {
            // Discharge / transfer / expired / AMA / LWBS all close the visit.
            $visit->board_status = 'done';
        }

        $visit->save();

        $detail = __('medemergency::lang.disp_' . $data['disposition']);
        if ($data['disposition'] === 'admitted') {
            $detail .= $handoff && $handoff['ok']
                ? ' → MedWard #' . $handoff['admission_id']
                : ' (' . __('medemergency::lang.admit_recorded_only') . ')';
        }
        MderVisitEvent::log($visit->id, 'disposition', $detail);

        return $this->ok(__('medemergency::lang.disposition_saved'), [
            'board_status' => $visit->board_status,
            'admit_url'    => $handoff['url'] ?? null,
            'admit_mode'   => $handoff['mode'] ?? null,
        ]);
    }
}
