import'server-only';
import{applyVerifiedStripeEvent}from'@/lib/billing-store';
type CheckoutSession={id?:string;mode?:string;payment_status?:string;customer?:string|null;metadata?:Record<string,string>};
type Subscription={id?:string;customer?:string;status?:string;metadata?:Record<string,string>;error?:{message?:string}};
export async function cancelReplacedSubscription(session:CheckoutSession,key:string){
 const oldId=session.metadata?.replacesSubscriptionId,userId=session.metadata?.userId;
 if(!oldId)return;
 if(!session.id||session.mode!=='subscription'||session.payment_status!=='paid'||!userId||typeof session.customer!=='string')throw Error('Replacement session is not confirmed');
 const oldResponse=await fetch(`https://api.stripe.com/v1/subscriptions/${encodeURIComponent(oldId)}`,{headers:{Authorization:`Bearer ${key}`},cache:'no-store'});
 const old=await oldResponse.json() as Subscription;
 if(!oldResponse.ok||old.id!==oldId||old.metadata?.userId!==userId||old.metadata?.productSlug!=='cash-app'||old.customer!==session.customer)throw Error('The previous plan could not be verified');
 if(old.status!=='canceled'){
  const cancelResponse=await fetch(`https://api.stripe.com/v1/subscriptions/${encodeURIComponent(oldId)}`,{method:'DELETE',headers:{Authorization:`Bearer ${key}`,'Idempotency-Key':`replace-${session.id}-${oldId}`},cache:'no-store'});
  const canceled=await cancelResponse.json() as Subscription;
  if(!cancelResponse.ok||canceled.id!==oldId||canceled.status!=='canceled')throw Error('The previous plan could not be ended');
 }
 applyVerifiedStripeEvent({id:`replace-old:${session.id}:${oldId}`,type:'customer.subscription.deleted',data:{object:{id:oldId,metadata:old.metadata||{userId,productSlug:'cash-app'}}}});
}
