import 'server-only';
import {applyVerifiedStripeEvent,currentPlan,type PurchasePlanKey} from './billing-store';
import {cancelReplacedSubscription} from './stripe-replacement';

export type CheckoutSession={
 id?:string;object?:string;mode?:string;status?:string;payment_status?:string;
 metadata?:Record<string,string>;client_reference_id?:string|null;
 customer?:string|null;customer_email?:string|null;
 subscription?:string|null;created?:number;amount_total?:number;
};
type StripeSubscription={id?:string;status?:string;customer?:string|null;metadata?:Record<string,string>;current_period_end?:number;cancel_at_period_end?:boolean;items?:{data?:Array<{current_period_end?:number}>}};
export class StripeLookupError extends Error{constructor(message:string,public status:number=502){super(message)}}
export async function stripeGET<T>(endpoint:string,key:string):Promise<T>{
 if(!endpoint.startsWith('/v1/'))throw new StripeLookupError('Unexpected billing endpoint',500);
 let response:Response;
 try{response=await fetch(`https://api.stripe.com${endpoint}`,{headers:{Authorization:`Bearer ${key}`},cache:'no-store',signal:AbortSignal.timeout(12000)})}
 catch{throw new StripeLookupError('Could not reach Stripe. Try again later.')}
 const json=await response.json().catch(()=>({})) as {error?:{message?:string}};
 if(!response.ok)throw new StripeLookupError(response.status===429?'Stripe is busy. Please try again shortly.':'Stripe could not verify this purchase.',response.status===429?429:502);
 return json as unknown as T;
}
export const validCheckoutId=(id:string)=>/^cs_(test|live)_[A-Za-z0-9]+$/.test(id);
const plans:PurchasePlanKey[]=['day1','day3','week','month','quarter','lifetime'];
export function belongsToAccount(session:CheckoutSession,userId:string){
 // Both identifiers are set when this website creates Checkout Sessions.
 // A matching email, receipt number or Stripe Customer is never sufficient.
 return session.metadata?.userId===userId&&session.client_reference_id===userId&&session.metadata.productSlug==='cash-app';
}
export async function verifyAndSyncCheckout(sessionId:string,userId:string,key:string,verifiedSession?:CheckoutSession){
 if(!validCheckoutId(sessionId))throw new StripeLookupError('Invalid Stripe checkout reference.',400);
 const session=verifiedSession||await stripeGET<CheckoutSession>(`/v1/checkout/sessions/${encodeURIComponent(sessionId)}`,key);
 if(session.id!==sessionId||!belongsToAccount(session,userId))return {state:'unlinked' as const};
 const plan=session.metadata?.plan as PurchasePlanKey;
 const expectedMode=['day1','day3','lifetime'].includes(plan)?'payment':'subscription';
 if(!plans.includes(plan)||session.mode!==expectedMode)return {state:'unlinked' as const};
 if(session.payment_status!=='paid'||session.status==='open'||session.status==='expired')return {state:'pending' as const};
 let subscription:StripeSubscription|undefined;
 if(expectedMode==='subscription'){
  if(typeof session.subscription!=='string'||!/^sub_[a-zA-Z0-9]+$/.test(session.subscription))return {state:'pending' as const};
  subscription=await stripeGET<StripeSubscription>(`/v1/subscriptions/${encodeURIComponent(session.subscription)}`,key);
  if(subscription.id!==session.subscription||subscription.customer!==session.customer||subscription.metadata?.userId!==userId||subscription.metadata?.plan!==plan)return {state:'unlinked' as const};
 }
 // This is the SAME fulfillment function used by signed webhooks and by the
 // post-checkout return page. Its persisted checkout ID prevents double grants.
 applyVerifiedStripeEvent({id:`stripe-verified:${sessionId}`,type:'checkout.session.completed',data:{object:session as unknown as Record<string,unknown>}});
 if(subscription)applyVerifiedStripeEvent({id:`stripe-reconcile-sub:${subscription.id}:${subscription.status}:${subscription.current_period_end||subscription.items?.data?.[0]?.current_period_end||0}:${subscription.cancel_at_period_end||false}`,type:'customer.subscription.updated',data:{object:subscription as unknown as Record<string,unknown>}});
 // Never cancel an old subscription before checking the new subscription with Stripe.
 if(subscription?.status==='active'||subscription?.status==='trialing')await cancelReplacedSubscription(session,key);
 return {state:'paid' as const,plan,active:currentPlan(userId).active};
}
export type StripeList<T>={data:T[];has_more?:boolean};
export async function findAccountCheckoutsByEmail(userId:string,email:string,key:string){
 // Searching by email only discovers candidates. Only exact account-linked
 // Checkout metadata can be used to grant or restore access.
 const query=new URLSearchParams({email,limit:'20'});
 const list=await stripeGET<StripeList<{id:string;email?:string}>>(`/v1/customers?${query}`,key);
 const matching=list.data.filter(x=>x.email===email&&/^cus_[a-zA-Z0-9]+$/.test(x.id)).slice(0,10);
 const sessions=new Set<string>();
 for(const customer of matching){
  const params=new URLSearchParams({customer:customer.id,limit:'100'});
  const rows=await stripeGET<StripeList<CheckoutSession>>(`/v1/checkout/sessions?${params}`,key);
  for(const s of rows.data||[])if(s.id&&belongsToAccount(s,userId)&&validCheckoutId(s.id))sessions.add(s.id);
 }
 return [...sessions];
}
