import 'server-only';
import fs from 'node:fs';
import path from 'node:path';
import {creditPromoPayment} from './promo-store';
import {trackAffiliate,affiliateSettings} from './platform-store';
import {creatorForUser,creatorRate} from './creator-store';
import {activeTrial,trialForUser} from './trial-store';
import {referralOwnerForCustomer} from './server-store';

export type PlanKey='day1'|'day3'|'week'|'month'|'quarter';
export const planKeys:PlanKey[]=['day1','day3','week','month','quarter'];
export const isDayPass=(plan:string):plan is 'day1'|'day3'=>plan==='day1'||plan==='day3';

export type PurchasePlanKey=PlanKey|'lifetime';
export type PlanSettings={priceCents:number;saleCents:number|null;enabled:boolean;includedApps:'all'|string[];features:string[]};
export type ProductSettings={free:boolean;enabled:boolean;allowedPlans:Record<PlanKey,boolean>};
export type BillingPackage={id:string;name:string;description:string;cycle:PlanKey;priceCents:number;saleCents:number|null;enabled:boolean;includedApps:'all'|string[];features:string[];sortOrder:number};
export type BillingConfig={version?:number;plans:Record<PlanKey,PlanSettings>;products:Record<string,ProductSettings>;packages:BillingPackage[]};
export type Purchase={userId:string;productSlug:string;plan:PurchasePlanKey;packageId?:string;active:boolean;expiresAt:number|null;stripeSubscription?:string;stripeCustomer?:string;cancelAtPeriodEnd?:boolean;updatedAt:string};
export type ManualPlan='free'|PlanKey;
export type PlanOverride={plan:ManualPlan;updatedAt:string;note:string;expiresAt:number|null};
type BillingState={purchases:Purchase[];processedEvents:string[];processedCheckouts?:string[];overrides?:Record<string,PlanOverride>};
const billingConfigPath=path.join(process.cwd(),'.local-data','billing-config.json');
const billingStatePath=path.join(process.cwd(),'.local-data','billing-state.json');
export const defaultBilling:BillingConfig={
 plans:{
  day1:{priceCents:299,saleCents:null,enabled:true,includedApps:'all',features:['24-hour one-time pass','Does not automatically renew']},
  day3:{priceCents:599,saleCents:null,enabled:true,includedApps:'all',features:['72-hour one-time pass','Does not automatically renew']},
  week:{priceCents:999,saleCents:null,enabled:true,includedApps:['cash-app','chase','discord'],features:['Choose 3 included app experiences','Create and save projects','Use the full editor for included apps']},
  month:{priceCents:2499,saleCents:null,enabled:true,includedApps:'all',features:['Access every available app experience','Create and save projects','Use all editing tools']},
  quarter:{priceCents:15000,saleCents:null,enabled:true,includedApps:'all',features:['Access every available app experience','Create and save projects','Use all editing tools','One charge every three months']}
 },
 products:{'cash-app':{free:false,enabled:true,allowedPlans:{day1:true,day3:true,week:true,month:true,quarter:true}}},
 packages:[
 {id:'pass-1-day',name:'1-Day Pass',description:'24-hour non-recurring access (owner can edit price).',cycle:'day1',priceCents:299,saleCents:null,enabled:true,includedApps:'all',features:['24 hours of access','One payment; no renewal'],sortOrder:0},
 {id:'pass-3-day',name:'3-Day Pass',description:'72-hour non-recurring access (owner can edit price).',cycle:'day3',priceCents:599,saleCents:null,enabled:true,includedApps:'all',features:['72 hours of access','One payment; no renewal'],sortOrder:1},
 {id:'starter-week',name:'Starter Plus',description:'A weekly pass to creative LARPs.',cycle:'week',priceCents:999,saleCents:null,enabled:true,includedApps:'all',features:['Use eligible LARP apps','Save creative previews'],sortOrder:2},
 {id:'creator-month',name:'Creator Plus',description:'Monthly creative access.',cycle:'month',priceCents:2499,saleCents:null,enabled:true,includedApps:'all',features:['Access all published LARP apps','Save and edit fictional projects'],sortOrder:3},
 {id:'studio-quarter',name:'Studio Plus',description:'Three months of creative access.',cycle:'quarter',priceCents:15000,saleCents:null,enabled:true,includedApps:'all',features:['All published LARP apps','Quarterly subscription'],sortOrder:4}]
};
function readJson<T>(filename:string,fallback:T):T{try{return JSON.parse(fs.readFileSync(filename,'utf8')) as T}catch{return fallback}}
function atomicWrite(filename:string,data:unknown){fs.mkdirSync(path.dirname(filename),{recursive:true});const tmp=filename+'.tmp';fs.writeFileSync(tmp,JSON.stringify(data,null,2),{mode:0o600});fs.renameSync(tmp,filename)}
export function billingConfig():BillingConfig{
 const cfg=readJson<Partial<BillingConfig>>(billingConfigPath,{});
 const plans={} as BillingConfig['plans'];
 const legacyPlans=cfg.plans as (Partial<BillingConfig['plans']>&{lifetime?:PlanSettings})|undefined;
 for(const key of planKeys){const saved=(key==='quarter'?legacyPlans?.quarter||legacyPlans?.lifetime:legacyPlans?.[key]) as Partial<PlanSettings>|undefined;plans[key]={...defaultBilling.plans[key],...(saved||{}),features:Array.isArray(saved?.features)?saved.features:defaultBilling.plans[key].features,includedApps:saved?.includedApps??defaultBilling.plans[key].includedApps};}
 const savedProduct=cfg.products?.['cash-app'] as (ProductSettings&{allowedPlans:Partial<Record<PlanKey|'lifetime',boolean>>})|undefined;
 const products={...defaultBilling.products,'cash-app':{...defaultBilling.products['cash-app'],...(savedProduct||{}),free:false,allowedPlans:{day1:savedProduct?.allowedPlans?.day1??true,day3:savedProduct?.allowedPlans?.day3??true,week:savedProduct?.allowedPlans?.week??true,month:savedProduct?.allowedPlans?.month??true,quarter:savedProduct?.allowedPlans?.quarter??savedProduct?.allowedPlans?.lifetime??true}}};
 let packages=Array.isArray(cfg.packages)?cfg.packages:defaultBilling.packages;
 // One-time restoration for previously installed projects. Earlier releases shipped
 // temporary passes hidden, or left them out of an already-saved v2 package list.
 // Preserve the owner's existing prices and other packages; only restore/publish
 // the two short passes. Version 3 remembers subsequent deliberate owner changes.
 const needsPassRestore=cfg.version!==3&&Array.isArray(cfg.packages);
 if(needsPassRestore){
  const existingPasses=packages.filter(p=>isDayPass(p.cycle));
  const restoredPasses=defaultBilling.packages.filter(p=>isDayPass(p.cycle)).map(def=>{
   const saved=existingPasses.find(p=>p.cycle===def.cycle);
   return saved?{...saved,enabled:true}:def;
  });
  const otherPackages=packages.filter(p=>!isDayPass(p.cycle)).sort((a,b)=>a.sortOrder-b.sortOrder);
  packages=[...restoredPasses,...otherPackages].map((p,i)=>({...p,sortOrder:i}));
 }
 const result:BillingConfig={version:3,plans,products,packages:packages.map(p=>({...p,includedApps:p.includedApps??'all'})).sort((a,b)=>a.sortOrder-b.sortOrder)};
 // Persist migration so hiding or removing a pass later in Owner Studio stays saved.
 if(needsPassRestore)atomicWrite(billingConfigPath,result);
 return result;
}
export function saveBillingConfig(config:BillingConfig){const updated={...config,version:3};atomicWrite(billingConfigPath,updated);return updated;}
function state(){return readJson<BillingState>(billingStatePath,{purchases:[],processedEvents:[]});}
export function effectivePrice(c:BillingConfig,plan:PlanKey){const p=c.plans[plan];return p.saleCents===null?p.priceCents:p.saleCents;}
export function hasAccess(userId:string,slug:string){return state().purchases.some(p=>p.userId===userId&&p.productSlug===slug&&p.active&&(p.expiresAt===null||p.expiresAt>Date.now()));}
export function canUseApp(userId:string,slug:string){
 if(!userId)return false;
 const c=billingConfig();const override=getPlanOverride(userId);
 // Explicit owner overrides always take priority over trial/creator rewards.
 if(override){if(override.plan==='free')return false;const included=c.plans[override.plan]?.includedApps;return included==='all'||Array.isArray(included)&&included.includes(slug)}
 // An explicit owner restriction takes priority; otherwise the three
 // named free demos can be saved with their persistent simulation mark.
 if(slug==='cash-app'||slug==='shopify'||slug==='youtube-studio')return true;
 if(creatorForUser(userId)||activeTrial(userId,slug))return true;
 const active=state().purchases.filter(p=>p.userId===userId&&p.active&&(p.expiresAt===null||p.expiresAt>Date.now()));
 return active.some(p=>{if(p.plan==='lifetime')return true;const pkg=c.packages.find(x=>x.id===p.packageId);const included=pkg?pkg.includedApps:c.plans[p.plan]?.includedApps;return included==='all'||Array.isArray(included)&&included.includes(slug)});
}
export function getPlanOverride(userId:string){const v=state().overrides?.[userId];return v&&(!v.expiresAt||v.expiresAt>Date.now())?v:null;}
export function setManualPlan(userId:string,plan:ManualPlan|null,note:string,expiresAt:number|null=null){const s=state();s.overrides=s.overrides||{};if(plan===null)delete s.overrides[userId];else s.overrides[userId]={plan,note:note.slice(0,200),expiresAt:expiresAt??(isDayPass(plan)?Date.now()+(plan==='day1'?1:3)*86400000:null),updatedAt:new Date().toISOString()};atomicWrite(billingStatePath,s);return s.overrides[userId]||null;}
export function currentPlan(userId:string){const override=getPlanOverride(userId);if(override)return{plan:override.plan,active:override.plan!=='free',source:'owner' as const,status:override.plan==='free'?'free':'owner_assigned',updatedAt:override.updatedAt,expiresAt:override.expiresAt};if(creatorForUser(userId))return{plan:'month' as const,active:true,source:'creator' as const,status:'creator_access' as const,updatedAt:creatorForUser(userId)!.updatedAt};const trial=trialForUser(userId);if(trial&&trial.expiresAt>Date.now())return{plan:'week' as const,active:true,source:'trial' as const,status:'trial_access' as const,updatedAt:new Date(trial.startedAt).toISOString(),expiresAt:trial.expiresAt};const latest=getPurchases(userId).filter(p=>p.active&&(p.expiresAt===null||p.expiresAt>Date.now())).sort((a,b)=>b.updatedAt.localeCompare(a.updatedAt))[0];return latest?{plan:latest.plan,active:true,source:'stripe' as const,status:latest.cancelAtPeriodEnd?'canceling':'active',updatedAt:latest.updatedAt,packageId:latest.packageId,packageName:billingConfig().packages.find(p=>p.id===latest.packageId)?.name}:{plan:'free' as const,active:false,source:'none' as const,status:'free',updatedAt:null};}
export function getServerPurchases(userId:string){return state().purchases.filter(p=>p.userId===userId);}
export function getPurchases(userId:string){return getServerPurchases(userId).map(p=>({...p,stripeCustomer:undefined}));}
export function getBillingCustomerIds(userId:string){return [...new Set(getServerPurchases(userId).map(p=>p.stripeCustomer).filter((x):x is string=>typeof x==='string'&&x.length>0))];}
export type StripeEvent={id:string;type:string;data:{object:Record<string,unknown>}};
export function applyVerifiedStripeEvent(event:StripeEvent){
 const s=state();if(s.processedEvents.includes(event.id))return;
 const obj=event.data.object;
 const metadata=(obj.metadata&&typeof obj.metadata==='object'?obj.metadata:{}) as Record<string,unknown>;
 const userId=String(metadata.userId||obj.client_reference_id||'');
 const slug=String(metadata.productSlug||'cash-app');
 const plan=String(metadata.plan||'') as PurchasePlanKey;const packageId=String(metadata.packageId||'');
 const findBySubscription=(id:string)=>s.purchases.filter(p=>p.stripeSubscription===id).sort((a,b)=>Date.parse(b.updatedAt)-Date.parse(a.updatedAt))[0];
 const savePurchase=(u:string,product:string,p:PurchasePlanKey,patch:Partial<Purchase>)=>{
  if(!u||![...planKeys,'lifetime'].includes(p)||product!=='cash-app')return;
  let purchase=s.purchases.find(x=>x.userId===u&&x.productSlug===product&&x.plan===p);
  if(!purchase){purchase={userId:u,productSlug:product,plan:p,active:false,expiresAt:0,updatedAt:new Date().toISOString()};s.purchases.push(purchase)}
  Object.assign(purchase,patch,{updatedAt:new Date().toISOString()});
 };
 if(['checkout.session.completed','checkout.session.async_payment_succeeded'].includes(event.type)&&obj.payment_status==='paid'){
  // Confirmation and webhook carry different event IDs for the same paid
  // Stripe Session: do not grant the duration twice.
  const checkoutId=String(obj.id||'');
  if(checkoutId&&s.processedCheckouts?.includes(checkoutId)){
   s.processedEvents=[event.id,...s.processedEvents].slice(0,2000);
   atomicWrite(billingStatePath,s);return;
  }
  if(checkoutId)s.processedCheckouts=[checkoutId,...(s.processedCheckouts||[])].slice(0,2000);
  if(typeof metadata.promoCode==='string'&&metadata.promoCode)creditPromoPayment(metadata.promoCode,String(obj.id||event.id));
  const referred=userId?referralOwnerForCustomer(userId):null;
  if(referred?.referralCode){const percent=creatorRate(referred.id)??affiliateSettings().commissionPercent;const amount=Math.max(0,Number(obj.amount_total||0));trackAffiliate('paid',referred.referralCode,referred.id,userId,{stripeEventId:String(obj.id||event.id),amountCents:amount,commissionCents:Math.floor(amount*percent/100)});}
  if(isDayPass(plan)&&obj.mode==='payment'){
   const duration=plan==='day1'?86400000:3*86400000;
   const existing=s.purchases.find(x=>x.userId===userId&&x.productSlug===slug&&x.plan===plan);
   const paidAt=Number.isFinite(Number(obj.created))&&Number(obj.created)>0?Number(obj.created)*1000:Date.now();
   // Reconciled purchases keep their ORIGINAL expiry; reopening an old receipt
   // must never grant a fresh 24/72 hours.
   const end=Math.max(paidAt,existing?.expiresAt||0)+duration;
   savePurchase(userId,slug,plan,{active:true,expiresAt:end,stripeCustomer:typeof obj.customer==='string'?obj.customer:undefined,packageId:packageId||undefined});
  }
  if(plan==='lifetime'&&obj.mode==='payment')savePurchase(userId,slug,'lifetime',{active:true,expiresAt:null,stripeCustomer:typeof obj.customer==='string'?obj.customer:undefined,packageId:packageId||undefined});
  else if((plan==='week'||plan==='month'||plan==='quarter')&&obj.mode==='subscription'){
   // Initial paid session; subscription.updated supplies Stripe's exact current period end.
   savePurchase(userId,slug,plan,{active:true,expiresAt:Date.now()+(plan==='week'?8:plan==='month'?32:93)*86400000,stripeSubscription:typeof obj.subscription==='string'?obj.subscription:undefined,stripeCustomer:typeof obj.customer==='string'?obj.customer:undefined,packageId:packageId||undefined});
  }
 }
 if(['customer.subscription.created','customer.subscription.updated','customer.subscription.deleted'].includes(event.type)){
  const subId=String(obj.id||'');const prior=findBySubscription(subId);
  const u=userId||prior?.userId||'';const product=metadata.productSlug?slug:prior?.productSlug||'cash-app';const level=(plan==='week'||plan==='month'||plan==='quarter')?plan:prior?.plan;
  if(level==='week'||level==='month'||level==='quarter'){
   const active=event.type!=='customer.subscription.deleted'&&['active','trialing'].includes(String(obj.status));
   const items=obj.items&&typeof obj.items==='object'?(obj.items as {data?:Array<{current_period_end?:number}>}):undefined;
   const period=Number(obj.current_period_end||items?.data?.[0]?.current_period_end||0)*1000;
   for(const old of s.purchases)if(old.stripeSubscription===subId&&old.plan!==level){old.active=false;old.expiresAt=Date.now();old.updatedAt=new Date().toISOString();}
   savePurchase(u,product,level,{active,expiresAt:period||Date.now(),stripeSubscription:subId,cancelAtPeriodEnd:obj.cancel_at_period_end===true});
  }
 }
 // invoice.payment_failed does not automatically cancel paid access: Stripe
 // subscription.status and current_period_end remain authoritative. The
 // signed webhook reconciles the live subscription after invoice events.
 s.processedEvents=[event.id,...s.processedEvents].slice(0,2000);
 atomicWrite(billingStatePath,s);
}

export function purgeUserBilling(userId:string){const s=state();s.purchases=s.purchases.filter(p=>p.userId!==userId);if(s.overrides)delete s.overrides[userId];atomicWrite(billingStatePath,s);}
