<?php

declare(strict_types=1);

namespace App\Services\Onboarding;

use App\Models\ManagedEnvironmentOnboardingSession;
use App\Support\Onboarding\OnboardingCheckpoint;
use App\Support\Onboarding\OnboardingDraftStage;
use App\Support\Onboarding\OnboardingLifecycleState;

class OnboardingDraftStageResolver
{
    public function __construct(
        private readonly OnboardingLifecycleService $lifecycleService,
    ) {}

    public function resolve(?ManagedEnvironmentOnboardingSession $draft): OnboardingDraftStage
    {
        if (! $draft instanceof ManagedEnvironmentOnboardingSession) {
            return OnboardingDraftStage::Identify;
        }

        $snapshot = $this->lifecycleService->snapshot($draft);
        $lifecycleState = $snapshot['lifecycle_state'];

        if ($lifecycleState === OnboardingLifecycleState::Cancelled) {
            return OnboardingDraftStage::Cancelled;
        }

        if ($lifecycleState === OnboardingLifecycleState::Completed) {
            return OnboardingDraftStage::Completed;
        }

        $checkpoint = $snapshot['current_checkpoint'];

        if ($checkpoint instanceof OnboardingCheckpoint) {
            return match ($checkpoint) {
                OnboardingCheckpoint::Identify => OnboardingDraftStage::Identify,
                OnboardingCheckpoint::ConnectProvider => OnboardingDraftStage::ConnectProvider,
                OnboardingCheckpoint::VerifyAccess => OnboardingDraftStage::VerifyAccess,
                OnboardingCheckpoint::Bootstrap => OnboardingDraftStage::Bootstrap,
                OnboardingCheckpoint::CompleteActivate => OnboardingDraftStage::Review,
            };
        }

        return match (OnboardingCheckpoint::fromCurrentStep($draft->current_step)) {
            OnboardingCheckpoint::ConnectProvider => OnboardingDraftStage::ConnectProvider,
            OnboardingCheckpoint::VerifyAccess => OnboardingDraftStage::VerifyAccess,
            OnboardingCheckpoint::Bootstrap => OnboardingDraftStage::Bootstrap,
            OnboardingCheckpoint::CompleteActivate => OnboardingDraftStage::Review,
            default => OnboardingDraftStage::Identify,
        };
    }
}
