import { initDatabase } from '@server/db/init';

export interface GatewayInfo {
  id: 'stripe' | 'razorpay';
  active: boolean;
  currency: string;
  promoCodesEnabled?: boolean;
  gracePeriodDays?: number;
}

export interface GatewayConfig {
  stripeActive: boolean;
  stripeCurrency: string;
  stripePromoCodesEnabled: boolean;
  paymentGracePeriodDays: number;
  razorpayActive: boolean;
  razorpayCurrency: string;
  razorpayKeyId: string | null;
  razorpayKeySecret: string | null;
}

export async function getGatewayConfig(): Promise<GatewayConfig> {
  await initDatabase();
  const { getPlatformSettings } = await import('@server/services/admin.service');
  const { getRazorpayCredentials } = await import('@server/lib/razorpay');
  const settings = await getPlatformSettings();
  const rzpCreds = await getRazorpayCredentials();
  return {
    stripeActive: (settings.stripe_active as boolean | undefined) ?? true,
    stripeCurrency: (settings.stripe_currency as string | undefined) ?? 'USD',
    stripePromoCodesEnabled: (settings.stripe_promo_codes_enabled as boolean | undefined) ?? false,
    paymentGracePeriodDays: (settings.payment_grace_period_days as number | undefined) ?? 3,
    razorpayActive: (settings.razorpay_active as boolean | undefined) ?? false,
    razorpayCurrency: (settings.razorpay_currency as string | undefined) ?? 'INR',
    razorpayKeyId: rzpCreds?.keyId ?? null,
    razorpayKeySecret: rzpCreds?.keySecret ?? null,
  };
}

export async function getActiveGateways(): Promise<GatewayInfo[]> {
  const cfg = await getGatewayConfig();
  const gateways: GatewayInfo[] = [];
  if (cfg.stripeActive) {
    gateways.push({
      id: 'stripe',
      active: true,
      currency: cfg.stripeCurrency.toUpperCase(),
      promoCodesEnabled: cfg.stripePromoCodesEnabled,
      gracePeriodDays: cfg.paymentGracePeriodDays,
    });
  }
  if (cfg.razorpayActive && cfg.razorpayKeyId && cfg.razorpayKeySecret) {
    gateways.push({
      id: 'razorpay',
      active: true,
      currency: cfg.razorpayCurrency.toUpperCase(),
    });
  }
  return gateways;
}
