import {membershipAccess} from '@/lib/membership';
import {identityFromHeaders} from '@/lib/identity';
import {headers} from 'next/headers';
import {paymentConfig,paymentOwner,paymentResponse,encryptConfig} from '@/lib/payment-config';
import {sameOrigin} from '@/lib/payfast';
import {database} from '@/db/store';
export async function GET(){const user=await identityFromHeaders(await headers());if(!user)return paymentResponse({error:'Please sign in.'},401);try{const c=await paymentConfig();const owner=user.email===paymentOwner;const subscriptions=await database().prepare('SELECT id,plan,status,mode,paid_until,cancelled_at FROM payment_subscriptions WHERE user_email=? ORDER BY created_at DESC').bind(user.email).all();return paymentResponse({access:await membershipAccess(user.email),owner,configured:!!c,ready:!!c?.enabled&&c.mode==='live',mode:c?.mode||null,merchantId:owner?c?.merchantId:undefined,subscriptions:subscriptions.results.map((s:any)=>({...s,status:s.status==='active'&&s.paid_until&&s.paid_until<=Date.now()?'overdue':s.status}))});}catch{return paymentResponse({error:'Payment settings could not be loaded. Please retry.'},503);}}
export async function POST(request:Request){const user=await identityFromHeaders(await headers());if(user?.email!==paymentOwner)return paymentResponse({error:'Only the Sovereign owner can connect Payfast.'},403);if(!sameOrigin(request))return paymentResponse({error:'Please save settings from Sovereign.'},403);try{const data:any=await request.json();if(!/^\d{8}$/.test(data.merchantId)||typeof data.merchantKey!=='string'||!/^[a-zA-Z0-9]{8,64}$/.test(data.merchantKey)||typeof data.passphrase!=='string'||data.passphrase.length<1||data.passphrase.length>100||!['sandbox','live'].includes(data.mode))return paymentResponse({error:'Enter your Merchant ID, Merchant Key and security passphrase.'},400);if(data.mode==='live'&&data.confirmed!==true)return paymentResponse({error:'Confirm that Payfast has approved your account and enabled recurring billing.'},400);const existing=await paymentConfig();if(existing&&(existing.merchantId!==data.merchantId||existing.mode!==data.mode)){const used=await database().prepare("SELECT id FROM payment_subscriptions WHERE status='active' OR (status='pending' AND created_at>?) LIMIT 1").bind(Date.now()-30*60*1000).first();if(used)return paymentResponse({error:'Existing payment attempts or subscriptions use this account. Contact support before switching accounts or modes.'},409);}const encrypted=await encryptConfig({merchantId:data.merchantId,merchantKey:data.merchantKey,passphrase:data.passphrase,mode:data.mode,enabled:true});await database().prepare("INSERT INTO payment_settings(id,encrypted) VALUES('payfast',?) ON CONFLICT(id) DO UPDATE SET encrypted=excluded.encrypted").bind(encrypted).run();return paymentResponse({saved:true});}catch{return paymentResponse({error:'Payfast settings could not be saved. Please retry.'},503);}}
