<?php

namespace App\Services\Care\Psychiatry;

/**
 * Map psychiatry / mental health clinical progress onto visit stages.
 */
class PsychiatryWorkflowService
{
    public const STAGE_CHECK_IN = 'check_in';

    public const STAGE_HISTORY = 'history';

    public const STAGE_RISK = 'risk';

    public const STAGE_FORMULATION = 'formulation';

    public const STAGE_REVIEW = 'review';

    public const STAGE_COMPLETED = 'completed';

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

        return self::STAGE_CHECK_IN;
    }

    /**
     * @param  array<string, mixed>  $payload
     */
    public function stageFromRisk(array $payload): string
    {
        $risk = trim((string) ($payload['risk_summary'] ?? $payload['risk'] ?? ''));
        if ($risk !== '') {
            return self::STAGE_RISK;
        }

        return self::STAGE_HISTORY;
    }

    /**
     * @param  array<string, mixed>  $payload
     */
    public function stageFromFormulation(array $payload): string
    {
        $plan = trim((string) ($payload['plan'] ?? ''));
        if ($plan !== '') {
            return self::STAGE_FORMULATION;
        }

        return self::STAGE_RISK;
    }

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

        return str_contains($outcome, 'discharged')
            || str_contains($outcome, 'follow-up arranged')
            || str_contains($outcome, 'completed');
    }

    /**
     * @return array<string, array{next: string, label: string}>
     */
    public function stageFlow(): array
    {
        return [
            self::STAGE_CHECK_IN => ['next' => self::STAGE_HISTORY, 'label' => 'Start history / MSE'],
            self::STAGE_HISTORY => ['next' => self::STAGE_RISK, 'label' => 'Move to risk assessment'],
            self::STAGE_RISK => ['next' => self::STAGE_FORMULATION, 'label' => 'Move to formulation / plan'],
            self::STAGE_FORMULATION => ['next' => self::STAGE_REVIEW, 'label' => 'Move to follow-up review'],
            self::STAGE_REVIEW => ['next' => self::STAGE_COMPLETED, 'label' => 'Complete visit'],
            self::STAGE_COMPLETED => ['next' => self::STAGE_COMPLETED, 'label' => 'Completed'],
        ];
    }
}
