<?php

namespace Fotogenic_AI;

if ( ! defined( 'ABSPATH' ) ) {
    exit;
}

/**
 * Config provider: in-memory cache → transient (storage) → GET /v2/configuration.
 * Fetch only when needed (auto_configure or product run). Trace config_source for run logs.
 */
final class Config_Provider {

    /** @var array|null In-memory cache. */
    private static $memory_cache = null;

    /**
     * Get configuration. Tries memory → transient → network.
     *
     * @return array{ data: array, source: string } data = config array, source = 'memory'|'storage'|'network'.
     */
    public static function get_config(): array {
        if ( null !== self::$memory_cache && is_array( self::$memory_cache ) ) {
            return [
                'data'   => self::$memory_cache,
                'source' => 'memory',
            ];
        }

        $cache_key = self::get_cache_key();
        $cached = get_transient( $cache_key );
        if ( is_array( $cached ) && isset( $cached['data'] ) ) {
            $config_service = new Service_Configuration();
            if ( $config_service->is_configuration_complete( $cached['data'] ) ) {
                self::$memory_cache = $cached['data'];
                return [
                    'data'   => $cached['data'],
                    'source' => 'storage',
                ];
            }
        }

        $response = Api_Client::instance()->request( 'GET', 'configuration' );
        if ( is_wp_error( $response ) ) {
            return [
                'data'   => [],
                'source' => 'network',
            ];
        }
        if ( ! is_array( $response ) ) {
            return [
                'data'   => [],
                'source' => 'network',
            ];
        }

        $config_service = new Service_Configuration();
        if ( ! $config_service->is_configuration_complete( $response ) ) {
            return [
                'data'   => $response,
                'source' => 'network',
            ];
        }

        self::$memory_cache = $response;
		set_transient( $cache_key, [ 'data' => $response ], 7 * DAY_IN_SECONDS );

        return [
            'data'   => $response,
            'source' => 'network',
        ];
    }

    /**
     * Clear in-memory cache (e.g. after refresh).
     */
    public static function clear_memory(): void {
        self::$memory_cache = null;
    }

    private static function get_cache_key(): string {
        return Service_Configuration::get_configuration_cache_key();
    }
}
