import { db } from '../../core/db.js';
import { getPaymentConfig } from '../../core/db.js';
import { decryptSecret } from '../../lib/secure.js';

// Muat config pembayaran sebuah guild dengan key SUDAH didekripsi.
// Return null kalau guild belum punya config.
export function loadGuildPaymentConfig(guildId) {
  const c = getPaymentConfig(guildId);
  if (!c) return null;
  return {
    guildId,
    autoDelivery: !!c.auto_delivery,
    tripayEnabled: !!c.tripay_enabled,
    midtransEnabled: !!c.midtrans_enabled,
    tripayApiKey: c.tripay_api_key_enc ? decryptSecret(c.tripay_api_key_enc) : null,
    tripayPrivateKey: c.tripay_private_key_enc ? decryptSecret(c.tripay_private_key_enc) : null,
    tripayMerchantCode: c.tripay_merchant_code || null,
    midtransServerKey: c.midtrans_server_key_enc ? decryptSecret(c.midtrans_server_key_enc) : null,
    midtransIsProduction: !!c.midtrans_is_production,
    pakasirEnabled: !!c.pakasir_enabled,
    pakasirSlug: c.pakasir_slug || null,
    pakasirApiKey: c.pakasir_api_key_enc ? decryptSecret(c.pakasir_api_key_enc) : null,
    manualMethods: c.manual_methods || null,
    qrisImageUrl: c.qris_image_url || null,
  };
}

// Dari invoice_id -> { order, guildId, ownerUserId }. Null kalau order gak ada.
export function resolveOrderContext(invoiceId) {
  const order = db.prepare('SELECT * FROM orders WHERE invoice_id = ?').get(invoiceId);
  if (!order) return null;
  const guild = db.prepare('SELECT owner_user_id FROM guilds WHERE guild_id = ?').get(order.guild_id);
  return { order, guildId: order.guild_id, ownerUserId: guild?.owner_user_id ?? null };
}
