<?php
if (!defined('ABSPATH')) exit;

/**
 * Class VMO_Service
 * Base class for external services with Circuit Breaker pattern.
 */
abstract class VMO_Service {
    protected $service_name;
    protected $failure_threshold = 3;
    protected $timeout_duration = 300; // 5 minutes in seconds

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

    /**
     * Check if the service is available (Circuit Breaker).
     */
    public function is_available() {
        $failures = get_transient("vmo_service_failures_{$this->service_name}");
        $last_failure = get_transient("vmo_service_last_failure_{$this->service_name}");

        if ($failures >= $this->failure_threshold) {
            // Check if timeout has passed
            if (time() - $last_failure < $this->timeout_duration) {
                return false; // Circuit is open (broken)
            } else {
                // Reset if timeout passed (Half-Open state)
                $this->reset_circuit();
            }
        }
        return true;
    }

    /**
     * Record a failure.
     */
    protected function record_failure($error_message = '') {
        $failures = (int) get_transient("vmo_service_failures_{$this->service_name}");
        $failures++;
        set_transient("vmo_service_failures_{$this->service_name}", $failures, DAY_IN_SECONDS);
        set_transient("vmo_service_last_failure_{$this->service_name}", time(), DAY_IN_SECONDS);
        
        error_log("VMO Service Failure ({$this->service_name}): {$error_message}. Count: {$failures}");
    }

    /**
     * Reset the circuit breaker.
     */
    protected function reset_circuit() {
        delete_transient("vmo_service_failures_{$this->service_name}");
        delete_transient("vmo_service_last_failure_{$this->service_name}");
    }

    /**
     * Get fallback response.
     */
    abstract protected function get_fallback();
}
