import {env} from '@/lib/hosting-env';
import {database} from '@/db/store';
export type PaymentConfig={merchantId:string;merchantKey:string;passphrase:string;mode:'sandbox'|'live';enabled:boolean};
export const paymentOwner='vanessa.magni01@gmail.com';
async function key(){if(!env.PAYMENT_CONFIG_KEY)throw Error('Payment setup unavailable');return crypto.subtle.importKey('raw',Uint8Array.from(atob(env.PAYMENT_CONFIG_KEY),c=>c.charCodeAt(0)),{name:'AES-GCM'},false,['encrypt','decrypt']);}
export async function encryptConfig(config:PaymentConfig){const iv=crypto.getRandomValues(new Uint8Array(12));const encrypted=await crypto.subtle.encrypt({name:'AES-GCM',iv},await key(),new TextEncoder().encode(JSON.stringify(config)));return btoa(String.fromCharCode(...iv,...new Uint8Array(encrypted)));}
export async function paymentConfig():Promise<PaymentConfig|null>{const row=await database().prepare("SELECT encrypted FROM payment_settings WHERE id='payfast'").first<{encrypted:string}>();if(!row)return null;const bytes=Uint8Array.from(atob(row.encrypted),c=>c.charCodeAt(0));return JSON.parse(new TextDecoder().decode(await crypto.subtle.decrypt({name:'AES-GCM',iv:bytes.slice(0,12)},await key(),bytes.slice(12))));}
export const paymentResponse=(data:unknown,status=200)=>Response.json(data,{status,headers:{'Cache-Control':'private, no-store'}});
