<?php

namespace App\Services\Care\Emergency;

/**
 * Map triage acuity / intent onto Emergency visit stages.
 */
class EmergencyWorkflowService
{
    public const STAGE_ARRIVAL = 'arrival';

    public const STAGE_RESUS = 'resus';

    public const STAGE_TREATMENT = 'treatment';

    public const STAGE_OBSERVATION = 'observation';

    public const STAGE_DISPOSITION = 'disposition';

    /**
     * Suggested next visit stage after a triage payload is saved.
     *
     * @param  array<string, mixed>  $payload
     */
    public function stageFromTriage(array $payload): string
    {
        $acuity = (string) ($payload['acuity'] ?? '');
        $intent = strtolower((string) ($payload['disposition_intent'] ?? ''));

        if (str_starts_with($acuity, '1') || str_starts_with($acuity, '2') || str_contains($intent, 'resus')) {
            return self::STAGE_RESUS;
        }

        if (str_contains($intent, 'observation')) {
            return self::STAGE_OBSERVATION;
        }

        if (str_contains($intent, 'discharge') || str_contains($intent, 'admit') || str_contains($intent, 'transfer')) {
            return self::STAGE_TREATMENT;
        }

        if (str_contains($intent, 'treatment')) {
            return self::STAGE_TREATMENT;
        }

        return self::STAGE_TREATMENT;
    }

    /**
     * Whether a disposition payload should close the visit episode.
     *
     * @param  array<string, mixed>  $payload
     */
    public function shouldCompleteVisit(array $payload): bool
    {
        $disposition = strtolower((string) ($payload['disposition'] ?? ''));

        return $disposition !== '';
    }

    /**
     * Default stage progression for action buttons.
     *
     * @return array<string, array{next: string, label: string}>
     */
    public function stageFlow(): array
    {
        return [
            self::STAGE_ARRIVAL => ['next' => self::STAGE_TREATMENT, 'label' => 'Move to treatment'],
            self::STAGE_RESUS => ['next' => self::STAGE_TREATMENT, 'label' => 'Move to treatment bay'],
            self::STAGE_TREATMENT => ['next' => self::STAGE_OBSERVATION, 'label' => 'Move to observation'],
            self::STAGE_OBSERVATION => ['next' => self::STAGE_DISPOSITION, 'label' => 'Ready for disposition'],
            self::STAGE_DISPOSITION => ['next' => self::STAGE_DISPOSITION, 'label' => 'Complete disposition'],
        ];
    }
}
