<?php

namespace App\Services\Care\Ambulance;

/**
 * Map ambulance / EMS clinical progress onto visit stages.
 */
class AmbulanceWorkflowService
{
    public const STAGE_CHECK_IN = 'check_in';

    public const STAGE_DISPATCH = 'dispatch';

    public const STAGE_ON_SCENE = 'on_scene';

    public const STAGE_TRANSPORT = 'transport';

    public const STAGE_HANDOVER = 'handover';

    public const STAGE_COMPLETED = 'completed';

    /**
     * @param  array<string, mixed>  $payload
     */
    public function stageFromDispatch(array $payload): string
    {
        if (! empty($payload['call_nature']) || ! empty($payload['location'])) {
            return self::STAGE_DISPATCH;
        }

        return self::STAGE_CHECK_IN;
    }

    /**
     * @param  array<string, mixed>  $payload
     */
    public function stageFromScene(array $payload): string
    {
        if (! empty($payload['scene_findings']) || ! empty($payload['chief_complaint'])) {
            return self::STAGE_ON_SCENE;
        }

        return self::STAGE_DISPATCH;
    }

    /**
     * @param  array<string, mixed>  $payload
     */
    public function stageFromEnRoute(array $payload): string
    {
        if (! empty($payload['interventions']) || ! empty($payload['destination'])) {
            return self::STAGE_TRANSPORT;
        }

        return self::STAGE_ON_SCENE;
    }

    /**
     * @param  array<string, mixed>  $payload
     */
    public function shouldCompleteVisit(array $payload): bool
    {
        $outcome = strtolower((string) ($payload['outcome'] ?? ''));

        return str_contains($outcome, 'completed')
            || str_contains($outcome, 'handed over')
            || str_contains($outcome, 'cancelled')
            || str_contains($outcome, 'refused');
    }

    /**
     * @return array<string, array{next: string, label: string}>
     */
    public function stageFlow(): array
    {
        return [
            self::STAGE_CHECK_IN => ['next' => self::STAGE_DISPATCH, 'label' => 'Dispatch'],
            self::STAGE_DISPATCH => ['next' => self::STAGE_ON_SCENE, 'label' => 'On scene'],
            self::STAGE_ON_SCENE => ['next' => self::STAGE_TRANSPORT, 'label' => 'Transport'],
            self::STAGE_TRANSPORT => ['next' => self::STAGE_HANDOVER, 'label' => 'Handover'],
            self::STAGE_HANDOVER => ['next' => self::STAGE_COMPLETED, 'label' => 'Complete'],
            self::STAGE_COMPLETED => ['next' => self::STAGE_COMPLETED, 'label' => 'Completed'],
        ];
    }
}
