import 'server-only';
import fs from 'node:fs';
import path from 'node:path';

// Private server-side index. Checkout Sessions are not proof of purchase until
// Stripe confirms they are paid. Never serve this index to the browser.
type CheckoutIndexRow = { id:string; userId:string; createdAt:number };
const filename = path.join(process.cwd(), '.local-data', 'stripe-checkouts.json');
function read():CheckoutIndexRow[]{
 try {const value=JSON.parse(fs.readFileSync(filename,'utf8')) as unknown;
  return Array.isArray(value)?value.filter((x):x is CheckoutIndexRow=>Boolean(x)&&typeof x.id==='string'&&typeof x.userId==='string'&&typeof x.createdAt==='number'):[];
 } catch {return []}
}
export function rememberStripeCheckout(userId:string,sessionId:string){
 if(!/^cs_(test|live)_[A-Za-z0-9]+$/.test(sessionId)||!userId)return;
 const records=read().filter(x=>x.id!==sessionId);
 records.push({userId,id:sessionId,createdAt:Date.now()});
 fs.mkdirSync(path.dirname(filename),{recursive:true});
 const temp=filename+'.tmp';fs.writeFileSync(temp,JSON.stringify(records.slice(-5000)),{mode:0o600});fs.renameSync(temp,filename);
}
export function checkoutsForUser(userId:string){
 return read().filter(x=>x.userId===userId).sort((a,b)=>b.createdAt-a.createdAt).slice(0,80).map(x=>x.id);
}
