/**
 * Runs the master's real gateway code (apps/api/platform/src/gateways.ts) against provider SANDBOXES.
 * Test keys come from the environment only and are never printed; live keys are refused.
 *
 *   STRIPE_TEST_SECRET_KEY=sk_test_...            Stripe: checkout, saved card auto-pay, decline, bank check, refund
 *   RAZORPAY_TEST_KEY_ID=rzp_test_... RAZORPAY_TEST_KEY_SECRET=...   Razorpay: payment link create + fetch
 *   PAYPAL_SANDBOX_CLIENT_ID=... PAYPAL_SANDBOX_SECRET=...           PayPal: order create (approval link)
 *
 *   npx tsx scripts/test-gateway-sandbox.ts
 *
 * Provider-hosted pages (card entry, PayPal approval) still need a person: the script prints those URLs
 * so the return/confirm path can be finished by hand in the browser with the provider's test card.
 */
import assert from 'node:assert/strict';
import { randomUUID } from 'node:crypto';
import { encryptSecret } from '../apps/api/platform/src/domain';
import { chargeSavedCard, createCheckout, refundPayment, refundState, savedStripeCard } from '../apps/api/platform/src/gateways';

const KEY = randomUUID().replace(/-/g, '') + randomUUID().replace(/-/g, '');
const config: any = { PLATFORM_ENCRYPTION_KEY: KEY, PLATFORM_WEB_ORIGIN: 'https://platform.localhost' };
const gateway = (publicKey: string, secret: string) => ({ mode: 'test' as const, publicKey, secretCiphertext: encryptSecret(secret, KEY), webhookSecretCiphertext: null });
const invoice = (currency: string) => ({ id: randomUUID(), number: `SANDBOX-${Date.now().toString(36)}`, totalMinor: 50_000, currency, description: 'Sandbox gateway check', buyer: { email: 'sandbox-owner@example.test', contactName: 'Sandbox Owner' } });
const results: string[] = [];
const pass = (line: string) => { results.push(`PASS ${line}`); console.log(`PASS ${line}`); };

async function stripe(secret: string) {
  if (!secret.startsWith('sk_test_')) throw new Error('STRIPE_TEST_SECRET_KEY must be a test key (sk_test_…).');
  const gw = gateway('pk_test', secret), auth = { Authorization: `Bearer ${secret}` };
  const post = async (path: string, form: Record<string, string>) => { const r = await fetch(`https://api.stripe.com/v1/${path}`, { method: 'POST', headers: { ...auth, 'Content-Type': 'application/x-www-form-urlencoded' }, body: new URLSearchParams(form) }); const body: any = await r.json(); if (!r.ok) throw new Error(`Stripe ${path}: ${body?.error?.message}`); return body; };

  const session = await createCheckout('stripe', gw, invoice('INR'), config, fetch, { saveCard: true });
  assert.match(session.checkoutId, /^cs_test_/);
  pass(`Stripe checkout with saved-card consent — finish by hand with card 4242 4242 4242 4242: ${session.url}`);

  // A customer with a test card attached, as a finished checkout leaves it.
  const customer = await post('customers', { email: 'sandbox-owner@example.test' });
  const card = async (token: string) => (await post(`payment_methods/${token}/attach`, { customer: customer.id })).id as string;

  const good = invoice('INR');
  const paid = await chargeSavedCard(gw, { customerId: customer.id, methodId: await card('pm_card_visa') }, good, config);
  assert.equal(paid?.invoiceId, good.id); assert.equal(paid?.amountMinor, good.totalMinor);
  pass(`Stripe off-session auto-pay charged ${paid!.reference}`);
  const label = await savedStripeCard(gw, paid!.reference, config);
  assert.equal(label?.customerId, customer.id);
  pass(`Stripe saved card read back: ${label!.label}`);

  await assert.rejects(chargeSavedCard(gw, { customerId: customer.id, methodId: await card('pm_card_chargeCustomerFail') }, invoice('INR'), config), /declined/i);
  pass('Stripe declined card is reported, not marked paid');
  await assert.rejects(chargeSavedCard(gw, { customerId: customer.id, methodId: await card('pm_card_authenticationRequired') }, invoice('INR'), config), /bank|authenticat/i);
  pass('Stripe card needing bank confirmation asks the owner to pay by hand');

  const refund = await refundPayment('stripe', gw, paid!.reference, 10_000, 'INR', config, `sandbox-${good.id}`);
  const state = refund.status === 'succeeded' ? 'succeeded' : await refundState('stripe', gw, refund.reference, paid!.reference, config);
  assert.notEqual(state, 'failed');
  pass(`Stripe partial refund ${refund.reference} (${state})`);
}

async function razorpay(id: string, secret: string) {
  if (!id.startsWith('rzp_test_')) throw new Error('RAZORPAY_TEST_KEY_ID must be a test key (rzp_test_…).');
  const gw = gateway(id, secret);
  const link = await createCheckout('razorpay', gw, invoice('INR'), config);
  const fetched: any = await (await fetch(`https://api.razorpay.com/v1/payment_links/${link.checkoutId}`, { headers: { Authorization: `Basic ${Buffer.from(`${id}:${secret}`).toString('base64')}` } })).json();
  assert.equal(fetched.status, 'created');
  pass(`Razorpay payment link created — pay by hand with a test card or UPI success@razorpay: ${link.url}`);
}

async function paypal(id: string, secret: string) {
  const gw = gateway(id, secret);
  const order = await createCheckout('paypal', gw, invoice('USD'), config);
  assert.match(order.url, /sandbox\.paypal\.com/);
  pass(`PayPal sandbox order created — approve by hand with a sandbox buyer: ${order.url}`);
}

async function main() {
  const env = process.env, ran: string[] = [];
  if (env.STRIPE_TEST_SECRET_KEY) { ran.push('stripe'); await stripe(env.STRIPE_TEST_SECRET_KEY); }
  if (env.RAZORPAY_TEST_KEY_ID && env.RAZORPAY_TEST_KEY_SECRET) { ran.push('razorpay'); await razorpay(env.RAZORPAY_TEST_KEY_ID, env.RAZORPAY_TEST_KEY_SECRET); }
  if (env.PAYPAL_SANDBOX_CLIENT_ID && env.PAYPAL_SANDBOX_SECRET) { ran.push('paypal'); await paypal(env.PAYPAL_SANDBOX_CLIENT_ID, env.PAYPAL_SANDBOX_SECRET); }
  if (!ran.length) { console.log('No sandbox keys set. See the header of this file.'); process.exitCode = 2; return; }
  console.log(`\n${results.length} checks passed for ${ran.join(', ')}.`);
}
main().catch(error => { console.error(`FAIL ${String(error?.message || error).replace(/sk_test_\w+|rzp_test_\w+/g, '[key]')}`); process.exitCode = 1; });
