import Razorpay from 'razorpay';

/**
 * Resolve active Razorpay credentials using this priority:
 * 1. If razorpay_mode is explicitly set → use the matching bucket only (strict)
 * 2. If razorpay_mode is NOT set (pre-migration):
 *    a. Only test bucket populated → use test
 *    b. Only live bucket populated → use live
 *    c. Neither bucket → fall back to legacy razorpay_key_id/key_secret
 */
async function getRazorpayCredentials(): Promise<{ keyId: string; keySecret: string } | null> {
  try {
    const { getPlatformSettings } = await import('@server/services/admin.service');
    const settings = await getPlatformSettings();

    const modeExplicit = settings.razorpay_mode as 'test' | 'live' | undefined;
    const testId     = settings.razorpay_test_key_id as string | undefined;
    const testSecret = settings.razorpay_test_key_secret as string | undefined;
    const liveId     = settings.razorpay_live_key_id as string | undefined;
    const liveSecret = settings.razorpay_live_key_secret as string | undefined;

    if (modeExplicit) {
      // Strict bucket selection — no cross-mode leak
      const keyId     = modeExplicit === 'test' ? testId     : liveId;
      const keySecret = modeExplicit === 'test' ? testSecret : liveSecret;
      if (keyId && keySecret) return { keyId, keySecret };
      return null;
    }

    // Mode not yet set: infer from available bucket keys
    if (testId && testSecret && !liveId) return { keyId: testId, keySecret: testSecret };
    if (liveId && liveSecret && !testId) return { keyId: liveId, keySecret: liveSecret };
    if (liveId && liveSecret) return { keyId: liveId, keySecret: liveSecret };

    // Pre-migration fallback
    const legacyId     = settings.razorpay_key_id as string | undefined;
    const legacySecret = settings.razorpay_key_secret as string | undefined;
    if (legacyId && legacySecret) return { keyId: legacyId, keySecret: legacySecret };
  } catch {
    // ignore
  }
  return null;
}

async function getRazorpayClient(): Promise<Razorpay | null> {
  const creds = await getRazorpayCredentials();
  if (!creds) return null;
  return new Razorpay({ key_id: creds.keyId, key_secret: creds.keySecret });
}

async function getRazorpayKeyId(): Promise<string | null> {
  const creds = await getRazorpayCredentials();
  return creds?.keyId ?? null;
}

export { getRazorpayClient, getRazorpayKeyId, getRazorpayCredentials };
