<?php

namespace App\Services\Care\Radiology;

/**
 * Map imaging clinical progress onto radiology visit stages.
 */
class RadiologyWorkflowService
{
    public const STAGE_CHECK_IN = 'check_in';

    public const STAGE_PROTOCOL = 'protocol';

    public const STAGE_ACQUISITION = 'acquisition';

    public const STAGE_REPORTING = 'reporting';

    public const STAGE_VERIFIED = 'verified';

    public const STAGE_COMPLETED = 'completed';

    /**
     * @param  array<string, mixed>  $payload
     */
    public function stageFromRequest(array $payload): string
    {
        if (! empty($payload['modality']) || ! empty($payload['body_part'])) {
            return self::STAGE_PROTOCOL;
        }

        return self::STAGE_CHECK_IN;
    }

    /**
     * @param  array<string, mixed>  $payload
     */
    public function stageFromAcquisition(array $payload): string
    {
        $status = strtolower((string) ($payload['acquisition_status'] ?? ''));
        if (str_contains($status, 'complete') || str_contains($status, 'acquired')) {
            return self::STAGE_ACQUISITION;
        }

        return self::STAGE_PROTOCOL;
    }

    /**
     * @param  array<string, mixed>  $payload
     */
    public function stageFromReport(array $payload): string
    {
        $findings = trim((string) ($payload['findings'] ?? ''));
        $impression = trim((string) ($payload['impression'] ?? ''));
        if ($findings !== '' || $impression !== '') {
            return self::STAGE_REPORTING;
        }

        return self::STAGE_ACQUISITION;
    }

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

        return str_contains($status, 'verified') || str_contains($status, 'final');
    }

    /**
     * @return array<string, array{next: string, label: string}>
     */
    public function stageFlow(): array
    {
        return [
            self::STAGE_CHECK_IN => ['next' => self::STAGE_PROTOCOL, 'label' => 'Start request / protocol'],
            self::STAGE_PROTOCOL => ['next' => self::STAGE_ACQUISITION, 'label' => 'Move to acquisition'],
            self::STAGE_ACQUISITION => ['next' => self::STAGE_REPORTING, 'label' => 'Move to reporting'],
            self::STAGE_REPORTING => ['next' => self::STAGE_VERIFIED, 'label' => 'Move to verification'],
            self::STAGE_VERIFIED => ['next' => self::STAGE_COMPLETED, 'label' => 'Complete study'],
            self::STAGE_COMPLETED => ['next' => self::STAGE_COMPLETED, 'label' => 'Completed'],
        ];
    }
}
