<?php
/**
 * Transient cache for provider API responses.
 *
 * Performance: third-party API calls are aggressively cached so
 * further calls are not throttled.
 *
 * @package CatalogPilot\AiStudio
 */

namespace CatalogPilot\AiStudio;

defined( 'ABSPATH' ) || exit;

final class Cache {

	const PREFIX   = 'cpais_cache_';
	const INDEX    = 'cpais_cache_index';
	const DEFAULT_TTL = 21600; // 6 hours.

	public static function enabled() {
		$settings = Settings::get_all();
		return ! empty( $settings['cache_enabled'] );
	}

	public static function ttl() {
		$settings = Settings::get_all();
		$ttl      = (int) ( $settings['cache_ttl'] ?? self::DEFAULT_TTL );
		return max( 60, min( 7 * DAY_IN_SECONDS, $ttl ) );
	}

	public static function key_for( $namespace, array $parts ) {
		ksort( $parts );
		$hash = md5( wp_json_encode( $parts ) );
		return self::PREFIX . sanitize_key( $namespace ) . '_' . $hash;
	}

	public static function get( $key ) {
		if ( ! self::enabled() ) {
			return null;
		}
		$value = get_transient( $key );
		return false === $value ? null : $value;
	}

	public static function set( $key, $value ) {
		if ( ! self::enabled() ) {
			return;
		}
		set_transient( $key, $value, self::ttl() );
		self::track( $key );
	}

	private static function track( $key ) {
		$index = get_option( self::INDEX, array() );
		if ( ! is_array( $index ) ) {
			$index = array();
		}
		$index[ $key ] = time();
		// Trim to last 500 to avoid unbounded growth.
		if ( count( $index ) > 500 ) {
			$index = array_slice( $index, -500, 500, true );
		}
		update_option( self::INDEX, $index, false );
	}

	public static function flush() {
		$index = get_option( self::INDEX, array() );
		if ( is_array( $index ) ) {
			foreach ( array_keys( $index ) as $k ) {
				delete_transient( $k );
			}
		}
		delete_option( self::INDEX );
		return true;
	}

	public static function size() {
		$index = get_option( self::INDEX, array() );
		return is_array( $index ) ? count( $index ) : 0;
	}
}
