<?php
/**
 * BookiFlex Onboarding Extension
 *
 * @package    BookiFlex
 * @subpackage Onboarding
 * @author     BookiFlex
 * @copyright  Copyright (c) 2025 BookiFlex
 * @license    GPL-2.0-or-later
 *
 * @link       https://bookiflex.com
 */

declare(strict_types=1);

namespace BookiFlex\Extensions\Onboarding\Service;

use BookiFlex\Extensions\Onboarding\Contract\OnboardingHandlerInterface;
use BookiFlex\Extensions\Onboarding\Contract\OnboardingPresetsProviderInterface;
use BookiFlex\Extensions\Onboarding\ValueObject\OnboardingConfiguration;
use BookiFlex\Extensions\Onboarding\ValueObject\OnboardingResult;
use BookiFlex\Extensions\Onboarding\ValueObject\NextStep;
use BookiFlex\Core\Service\CptCreator\CptCreatorInterface;

defined( 'ABSPATH' ) || exit;

/**
 * Manual Configuration Handler
 *
 * Handles Manual Configuration onboarding mode.
 * Does NOT create any entities - user will configure manually.
 * Returns next steps pointing to relevant configuration pages.
 *
 * @package BookiFlex\Extensions\Onboarding\Service
 * @since   1.0.0
 */
class ManualConfigHandler implements OnboardingHandlerInterface
{
    /**
     * ManualConfigHandler constructor
     *
     * @param OnboardingPresetsProviderInterface $presetsProvider Presets provider
     */
    public function __construct(
        private readonly OnboardingPresetsProviderInterface $presetsProvider
    ) {
    }

    /**
     * Handle Manual Configuration onboarding
     *
     * @param  OnboardingConfiguration $config       Onboarding configuration
     * @param  CptCreatorInterface     $cptCreator   CPT creator service (unused)
     * @param  OnboardingStateManager  $stateManager State manager
     * @return OnboardingResult Execution result with next steps
     */
    public function handle(
        OnboardingConfiguration $config,
        CptCreatorInterface $cptCreator,
        OnboardingStateManager $stateManager
    ): OnboardingResult {
        // Get next steps from presets provider
        $nextSteps = $this->buildNextSteps(
            $this->presetsProvider->getNextStepsForMode($config->mode)
        );

        return new OnboardingResult(
            success: true,
            mode: $config->mode,
            nextSteps: $nextSteps
        );
    }

    /**
     * Build NextStep value objects from preset data
     *
     * @param  array<int, array<string, string>> $presetSteps Preset next steps
     * @return NextStep[] Array of NextStep objects
     */
    private function buildNextSteps(array $presetSteps): array
    {
        $steps = [];

        foreach ($presetSteps as $step) {
            if (isset($step['title'], $step['description'], $step['icon'])) {
                $steps[] = new NextStep(
                    title: $step['title'],
                    description: $step['description'],
                    icon: $step['icon']
                );
            }
        }

        return $steps;
    }
}
