// config/paypal.js
import paypal from '@paypal/checkout-server-sdk';

/**
 * Returns PayPal HTTP client instance with Environment that has access
 * credentials context. Use this instance to invoke PayPal APIs, provided the
 * credentials have access.
 * 
 * NOTE: Using deprecated SDK temporarily due to authentication issues with new SDK
 * TODO: Migrate to @paypal/paypal-server-sdk once auth issue is resolved
 */
function client() {
  const clientId = process.env.PAYPAL_CLIENT_ID;
  const clientSecret = process.env.PAYPAL_CLIENT_SECRET;
  const environment = process.env.PAYPAL_MODE || 'sandbox';

  if (!clientId || !clientSecret) {
    throw new Error('PAYPAL_CLIENT_ID and PAYPAL_CLIENT_SECRET must be set in environment variables');
  }

  // Choose environment based on configuration
  let paypalEnvironment;
  if (environment === 'production') {
    paypalEnvironment = new paypal.core.LiveEnvironment(clientId, clientSecret);
    console.log('✅ PayPal configured in PRODUCTION mode');
  } else {
    paypalEnvironment = new paypal.core.SandboxEnvironment(clientId, clientSecret);
    console.log('✅ PayPal configured in SANDBOX mode');
  }

  return new paypal.core.PayPalHttpClient(paypalEnvironment);
}

export default client;
