<?php

namespace App\Services\Care\ChildWelfare;

/**
 * Map child welfare / CWC clinical progress onto visit stages.
 */
class ChildWelfareWorkflowService
{
    public const STAGE_CHECK_IN = 'check_in';

    public const STAGE_INTAKE = 'intake';

    public const STAGE_ASSESSMENT = 'assessment';

    public const STAGE_PLAN = 'plan';

    public const STAGE_FOLLOWUP = 'followup';

    public const STAGE_COMPLETED = 'completed';

    /**
     * @param  array<string, mixed>  $payload
     */
    public function stageFromIntake(array $payload): string
    {
        $history = trim((string) ($payload['history'] ?? ''));
        if ($history !== '' || ! empty($payload['visit_reason'])) {
            return self::STAGE_INTAKE;
        }

        return self::STAGE_CHECK_IN;
    }

    /**
     * @param  array<string, mixed>  $payload
     */
    public function stageFromAssessment(array $payload): string
    {
        if (! empty($payload['exam_findings']) || ! empty($payload['assessment_summary'])) {
            return self::STAGE_ASSESSMENT;
        }

        return self::STAGE_INTAKE;
    }

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

        return self::STAGE_ASSESSMENT;
    }

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

        return str_contains($outcome, 'completed')
            || str_contains($outcome, 'referred')
            || str_contains($outcome, 'lost to follow-up');
    }

    /**
     * @return array<string, array{next: string, label: string}>
     */
    public function stageFlow(): array
    {
        return [
            self::STAGE_CHECK_IN => ['next' => self::STAGE_INTAKE, 'label' => 'Start intake'],
            self::STAGE_INTAKE => ['next' => self::STAGE_ASSESSMENT, 'label' => 'Move to assessment'],
            self::STAGE_ASSESSMENT => ['next' => self::STAGE_PLAN, 'label' => 'Move to care plan'],
            self::STAGE_PLAN => ['next' => self::STAGE_FOLLOWUP, 'label' => 'Move to intervention / follow-up'],
            self::STAGE_FOLLOWUP => ['next' => self::STAGE_COMPLETED, 'label' => 'Complete visit'],
            self::STAGE_COMPLETED => ['next' => self::STAGE_COMPLETED, 'label' => 'Completed'],
        ];
    }
}
