<?php

namespace WPSN\Modules\Onboarding;

use WPSN\Core\Settings;
use WPSN\Modules\IndexNow\IndexNowSecretsRepository;
use WPSN\Modules\SearchConsole\SearchConsoleSecretsRepository;

defined('ABSPATH') || exit;

/**
 * Resolves the live onboarding checklist state from current settings + secrets.
 *
 * This keeps the Setup Wizard and Tasks Hub in sync.
 */
final class OnboardingChecklistRuntime
{
    private Settings $settings;

    public function __construct(Settings $settings)
    {
        $this->settings = $settings;
    }

    /**
     * @return array{items:array<int,array<string,mixed>>,summary:array<string,int>}
     */
    public function snapshot(): array
    {
        $builder = new OnboardingChecklistBuilder($this->settings);
        $items = $builder->build($this->context());
        $items = (new OnboardingChecklistStateRepository())->apply($items);

        return [
            'items' => $items,
            'summary' => $builder->summary($items),
        ];
    }

    /**
     * @return array<int,array<string,mixed>>
     */
    public function items(): array
    {
        $snapshot = $this->snapshot();
        return isset($snapshot['items']) && is_array($snapshot['items']) ? $snapshot['items'] : [];
    }

    /**
     * @return array<string,int>
     */
    public function summary(): array
    {
        $snapshot = $this->snapshot();
        return isset($snapshot['summary']) && is_array($snapshot['summary']) ? $snapshot['summary'] : [];
    }

    /**
     * @return array<string,mixed>
     */
    private function context(): array
    {
        $gscSecrets = new SearchConsoleSecretsRepository();
        $indexNowSecrets = new IndexNowSecretsRepository();

        return [
            'gsc_connected' => $gscSecrets->hasClient() && $gscSecrets->hasRefreshToken(),
            'indexnow_has_key' => $indexNowSecrets->hasKey(),
        ];
    }
}
