<?php

declare(strict_types=1);

namespace App\Services\SupportCenter;

use DBCore\Setting\Contracts\SettingManagerInterface;

/**
 * 持久化最近一次接入码确认尝试快照。
 */
final class HostSiteOnboardingLastAttemptStore
{
    public const SETTING_KEY = 'dberp.host.site_onboarding.last_attempt_snapshot';

    public function __construct(
        private readonly SettingManagerInterface $settingManager,
    ) {}

    /**
     * @return array<string, mixed>|null
     */
    public function get(): ?array
    {
        $value = $this->settingManager->get(self::SETTING_KEY);

        return is_array($value) ? $value : null;
    }

    public function latestTaskNo(): ?string
    {
        $snapshot = $this->get();
        $taskNo = $snapshot['task_no'] ?? null;

        return is_string($taskNo) && trim($taskNo) !== '' ? trim($taskNo) : null;
    }

    /**
     * @param  array<string, mixed>  $snapshot
     */
    public function store(array $snapshot): void
    {
        $this->settingManager->set(
            self::SETTING_KEY,
            SupportCenterSnapshotSanitizer::sanitize($snapshot),
        );
    }
}
