<?php

declare(strict_types=1);

namespace SeoScope\Services;

/**
 * JSON shape persisted in {@see \SeoScope\Repositories\DashboardCacheRepository} for the
 * dashboard SEO AI Assistant (M3 #4 — same table as deferred widgets; namespaced keys).
 *
 * Widget rows use opaque keys (`trend`, `traffic`, …). Assistant rows use
 * {@see SeoAiAssistantCacheKey} for `group_key` and this envelope inside `payload_json`.
 */
final class SeoAiAssistantDashboardCacheEnvelope
{
    /** Int version of this stored-object contract (bump only if wrapping changes). */
    public const RESPONSE_FORMAT_VERSION_KEY = 'seo_ai_response_ver';

    public const RESPONSE_BODY_KEY = 'body';

    public const FORMAT_V1 = 1;

    /**
     * @param array<string, mixed> $apiBody Same shape echoed to the client on LLM success (incl. ok, texts, seo_health, …)
     *
     * @return array<string, mixed>
     */
    public static function wrapStoredPayload(array $apiBody): array
    {
        return [
            self::RESPONSE_FORMAT_VERSION_KEY => self::FORMAT_V1,
            self::RESPONSE_BODY_KEY => $apiBody,
        ];
    }

    /**
     * @param array<string, mixed> $decodedRow payload_json decoded (may include other feature keys if misused)
     */
    public static function isAssistantEnvelopeV1(array $decodedRow): bool
    {
        return (int) ($decodedRow[self::RESPONSE_FORMAT_VERSION_KEY] ?? 0) === self::FORMAT_V1
            && isset($decodedRow[self::RESPONSE_BODY_KEY])
            && is_array($decodedRow[self::RESPONSE_BODY_KEY]);
    }
}
