<?php
/**
 * API Client Factory
 *
 * Returns appropriate API client based on configuration.
 * Implements Factory pattern for dependency injection.
 */

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

class PSFA_API_Factory {

    /**
     * Cached client instance
     *
     * @var PSFA_API_Client_Interface|null
     */
    private static $instance = null;

    /**
     * Get the appropriate API client based on configuration
     *
     * @return PSFA_API_Client_Interface
     */
    public static function get_client(): PSFA_API_Client_Interface {
        if (self::$instance !== null) {
            return self::$instance;
        }

        $auth_type = get_option('psfa_auth_type', 'awssig4');

        if ($auth_type === 'oauth' && self::is_oauth_configured()) {
            require_once __DIR__ . '/class-oauth-client.php';
            self::$instance = new PSFA_OAuth_Client();
        } else {
            require_once __DIR__ . '/class-awssig4-client.php';
            self::$instance = new PSFA_AWSSig4_Client();
        }

        return self::$instance;
    }

    /**
     * Check if OAuth credentials are configured
     *
     * @return bool
     */
    private static function is_oauth_configured(): bool {
        $client_id = get_option('psfa_oauth_client_id', '');
        $client_secret = get_option('psfa_oauth_client_secret', '');
        return !empty($client_id) && !empty($client_secret);
    }

    /**
     * Check if AWS Sig V4 credentials are configured
     *
     * @return bool
     */
    public static function is_awssig4_configured(): bool {
        $access_key = get_option('psfa_access_key_id', '');
        $secret_key = get_option('psfa_secret_access_key', '');
        $associate_tag = get_option('psfa_associate_tag', '');
        return !empty($access_key) && !empty($secret_key) && !empty($associate_tag);
    }

    /**
     * Reset cached instance (useful for testing or switching auth types)
     */
    public static function reset(): void {
        self::$instance = null;
    }

    /**
     * Get current auth type
     *
     * @return string 'awssig4' or 'oauth'
     */
    public static function get_auth_type(): string {
        return get_option('psfa_auth_type', 'awssig4');
    }

    /**
     * Set auth type and reset cached client
     *
     * @param string $type 'awssig4' or 'oauth'
     */
    public static function set_auth_type(string $type): void {
        if (in_array($type, ['awssig4', 'oauth'], true)) {
            update_option('psfa_auth_type', $type);
            self::reset();
        }
    }
}
