import type { RepositorySql } from '../repositories/db'; import type { CreditPurchaseSnapshot } from './pay0-credit-verification'; import { withCreditTenant } from './credit-tenant-scope'; interface PurchaseRow { tenant_id: string; purchase_id: string; checkout_session_id: string; amount_minor: string; currency: string; credits: string; } function fromRow(row: PurchaseRow): CreditPurchaseSnapshot { return { tenantId: row.tenant_id, purchaseId: row.purchase_id, checkoutSessionId: row.checkout_session_id, amountMinor: Number(row.amount_minor), currency: row.currency, credits: Number(row.credits), }; } /** Server-internal snapshot storage. Callers must authenticate and price orders before create. */ export class PostgresCreditPurchaseStore { constructor(private readonly sql: RepositorySql) {} async create(snapshot: CreditPurchaseSnapshot): Promise { if ( ![snapshot.tenantId, snapshot.purchaseId, snapshot.checkoutSessionId].every( (s) => typeof s === 'string' && s.trim(), ) || !Number.isSafeInteger(snapshot.amountMinor) || snapshot.amountMinor <= 0 || !Number.isSafeInteger(snapshot.credits) || snapshot.credits <= 0 || !/^[A-Z]{3}$/.test(snapshot.currency) ) { throw new Error('Invalid credit purchase snapshot'); } return withCreditTenant(this.sql, snapshot.tenantId, async (tx) => { const rows = await tx` INSERT INTO opt_credit_purchases (tenant_id, purchase_id, checkout_session_id, amount_minor, currency, credits) VALUES (${snapshot.tenantId}, ${snapshot.purchaseId}, ${snapshot.checkoutSessionId}, ${snapshot.amountMinor}, ${snapshot.currency}, ${snapshot.credits}) ON CONFLICT (tenant_id, purchase_id) DO NOTHING RETURNING *`; if (rows[0]) return fromRow(rows[0]); const existingRows = await tx` SELECT * FROM opt_credit_purchases WHERE tenant_id = ${snapshot.tenantId} AND purchase_id = ${snapshot.purchaseId}`; const existing = existingRows[0] ? fromRow(existingRows[0]) : undefined; if (!existing || existing.checkoutSessionId !== snapshot.checkoutSessionId || existing.amountMinor !== snapshot.amountMinor || existing.currency !== snapshot.currency || existing.credits !== snapshot.credits) { throw new Error('Purchase id reused for a different price snapshot'); } return existing; }); } async get(tenantId: string, purchaseId: string): Promise { if (typeof purchaseId !== 'string' || !purchaseId.trim()) throw new Error('Invalid credit purchase id'); return withCreditTenant(this.sql, tenantId, async (tx) => { const rows = await tx`SELECT * FROM opt_credit_purchases WHERE tenant_id = ${tenantId} AND purchase_id = ${purchaseId}`; return rows[0] ? fromRow(rows[0]) : undefined; }); } }