import { collection, addDoc, serverTimestamp } from 'firebase/firestore';
import { db } from './firebase.js';

const pendingRef = collection(db, 'pendingDonations');

const IS_DEV = import.meta.env.DEV;

const MERCHANT_HANDLE = IS_DEV
  ? 'dominica-methodist-circuit-dev'
  : 'dominica-methodist-circuit';

const PAYMENT_BASE_URL = IS_DEV
  ? 'https://pay-dm-dev.web.app'
  : 'https://pay.shopdm.store';

export async function createPendingDonation({ name, amount, classYear, message, anonymous }) {
  const docRef = await addDoc(pendingRef, {
    name: anonymous ? 'Anonymous' : name,
    amount: Number(amount),
    classYear: classYear || '',
    message: message || '',
    anonymous: !!anonymous,
    status: 'pending',
    env: IS_DEV ? 'dev' : 'production',
    createdAt: serverTimestamp(),
  });
  return docRef.id;
}

export function buildPaymentUrl(pendingId, amount, donorName) {
  const totalXcd = Number(amount).toFixed(2);
  const reason = `WHS 100th Anniversary Donation - ${donorName}`;
  const params = new URLSearchParams({
    total_xcd: totalXcd,
    reason: reason,
    invoice_id: pendingId,
    redirect: 'true',
    webhook: 'true',
  });
  return `${PAYMENT_BASE_URL}/${MERCHANT_HANDLE}?${params.toString()}`;
}
