import 'server-only';
import fs from 'node:fs';import path from 'node:path';import {randomUUID} from 'node:crypto';
export type Promo={code:string;percentOff:number;enabled:boolean;expiresAt:number|null;maxRedemptions:number|null;redemptions:number;createdAt:string};
export type UpgradeRequest={id:string;userId:string;email:string;type:'tiktok_video'|'tiktok_account'|'partnership'|'game_reward';detail:string;status:'pending'|'approved'|'rejected';createdAt:string;reviewedAt?:string};
type Data={promos:Promo[];requests:UpgradeRequest[];processedPayments:string[]};
const file=path.join(process.cwd(),'.local-data','promotions.json');
const read=():Data=>{try{const v=JSON.parse(fs.readFileSync(file,'utf8')) as Data;return{promos:v.promos||[],requests:v.requests||[],processedPayments:v.processedPayments||[]}}catch{return{promos:[],requests:[],processedPayments:[]}}};
const write=(v:Data)=>{fs.mkdirSync(path.dirname(file),{recursive:true});const tmp=file+'.tmp';fs.writeFileSync(tmp,JSON.stringify(v,null,2),{mode:0o600});fs.renameSync(tmp,file)};
export function promos(){return read().promos}
export function availablePromo(raw:string){const p=read().promos.find(p=>p.code===raw.trim().toUpperCase());return p&&p.enabled&&(!p.expiresAt||p.expiresAt>Date.now())&&(p.maxRedemptions===null||p.redemptions<p.maxRedemptions)?p:null}
export function changePromo(data:{operation:string;code:string;percentOff?:number;enabled?:boolean;expiresAt?:number|null;maxRedemptions?:number|null}){const s=read(),code=data.code.trim().toUpperCase();if(!/^[A-Z0-9_-]{3,32}$/.test(code))throw Error('Use 3–32 letters, numbers, hyphens, or underscores');const existing=s.promos.find(p=>p.code===code);if(data.operation==='delete'){s.promos=s.promos.filter(p=>p.code!==code);write(s);return s.promos}if(data.operation!=='save')throw Error('Invalid operation');const percentage=Number(data.percentOff);if(!Number.isInteger(percentage)||percentage<1||percentage>90)throw Error('Discount must be between 1% and 90%');if(data.maxRedemptions!==null&&(!Number.isInteger(data.maxRedemptions)||Number(data.maxRedemptions)<1||Number(data.maxRedemptions)>100000))throw Error('Invalid redemption limit');if(data.expiresAt!==null&&(!Number.isFinite(data.expiresAt)||Number(data.expiresAt)<=Date.now()))throw Error('Expiry must be in the future');if(existing)Object.assign(existing,{percentOff:percentage,enabled:data.enabled===true,expiresAt:data.expiresAt??null,maxRedemptions:data.maxRedemptions??null});else s.promos.push({code,percentOff:percentage,enabled:data.enabled===true,expiresAt:data.expiresAt??null,maxRedemptions:data.maxRedemptions??null,redemptions:0,createdAt:new Date().toISOString()});write(s);return s.promos}
export function creditPromoPayment(raw:string,paymentId:string){const s=read();if(s.processedPayments.includes(paymentId))return;const promo=s.promos.find(p=>p.code===raw.trim().toUpperCase());if(!promo)return;promo.redemptions++;s.processedPayments.push(paymentId);s.processedPayments=s.processedPayments.slice(-5000);write(s)}
export function submitUpgrade(userId:string,email:string,type:UpgradeRequest['type'],detail:string){const s=read();if(s.requests.some(r=>r.userId===userId&&r.status==='pending'&&r.type===type))throw Error('You already have a pending request of this type');const request:UpgradeRequest={id:randomUUID(),userId,email,type,detail:detail.trim().slice(0,600),status:'pending',createdAt:new Date().toISOString()};s.requests.push(request);write(s);return request}
export function upgradeRequests(){return read().requests.slice().reverse()}
export function reviewUpgrade(id:string,status:'approved'|'rejected'){const s=read();const r=s.requests.find(x=>x.id===id);if(!r)throw Error('Request not found');if(r.status!=='pending')throw Error('Already reviewed');r.status=status;r.reviewedAt=new Date().toISOString();write(s);return r}
