// ---------------------------------------------------------------------------
// Subscription API client  (client-side)
// ---------------------------------------------------------------------------

import { apiFetch } from './client';

// ---------------------------------------------------------------------------
// Request / response shapes
// TODO: import from @/lib/types once the shared types package is finalised
// ---------------------------------------------------------------------------

export interface SubscriptionResponse {
  id: number;
  user_id: number;
  tier: string;
  status: string;
  platform: string;
  product_id: string;
  original_transaction_id: string;
  expires_at?: string;
  cancelled_at?: string;
  created_at: string;
  updated_at: string;
}

export interface SubscriptionStatusResponse {
  tier: string;
  is_active: boolean;
  subscribed_at?: string;
  expires_at?: string;
  auto_renew: boolean;
  trial_start?: string | null;
  trial_end?: string | null;
  trial_active?: boolean;
  subscription_source?: string;
  usage?: UsageResponse | null;
  limits: Record<string, TierLimitsResponse>;
  limitations_enabled: boolean;
}

export interface TierLimitsResponse {
  properties: number | null;
  tasks: number | null;
  contractors: number | null;
  documents: number | null;
}

export interface UsageResponse {
  residences?: number;
  tasks?: number;
  contractors?: number;
  documents?: number;
}

export interface UpgradeTriggerResponse {
  trigger_key: string;
  title: string;
  message: string;
  promo_html: string;
  button_text: string;
}

export interface FeatureBenefitResponse {
  feature_name: string;
  free_tier_text: string;
  pro_tier_text: string;
  display_order: number;
}

export interface PromotionResponse {
  id: number;
  title: string;
  description: string;
  discount_percentage: number;
  promo_code: string;
  valid_from: string;
  valid_until: string;
}

export interface ProcessPurchaseRequest {
  platform: 'ios' | 'android';
  receipt_data?: string;
  transaction_id?: string;
  purchase_token?: string;
  product_id?: string;
}

export interface PurchaseResponse {
  message: string;
  subscription: SubscriptionResponse;
}

export interface MessageResponse {
  message: string;
}

// ---------------------------------------------------------------------------
// API functions
// ---------------------------------------------------------------------------

/** Get the current user's subscription details. */
export function getSubscription(): Promise<SubscriptionResponse> {
  return apiFetch<SubscriptionResponse>('/subscription/');
}

/** Get the current user's subscription status with tier limits. */
export function getSubscriptionStatus(): Promise<SubscriptionStatusResponse> {
  return apiFetch<SubscriptionStatusResponse>('/subscription/status/');
}

/** Get a specific upgrade trigger by key. */
export function getUpgradeTrigger(
  key: string,
): Promise<UpgradeTriggerResponse> {
  return apiFetch<UpgradeTriggerResponse>(
    `/subscription/upgrade-trigger/${key}/`,
  );
}

/** Get all upgrade triggers (public, no auth required). */
export function getAllUpgradeTriggers(): Promise<UpgradeTriggerResponse[]> {
  return apiFetch<UpgradeTriggerResponse[]>(
    '/subscription/upgrade-triggers/',
  );
}

/** Get feature benefits for the subscription tiers. */
export function getFeatureBenefits(): Promise<FeatureBenefitResponse[]> {
  return apiFetch<FeatureBenefitResponse[]>('/subscription/features/');
}

/** Get active promotions for the current user. */
export function getPromotions(): Promise<PromotionResponse[]> {
  return apiFetch<PromotionResponse[]>('/subscription/promotions/');
}

/** Process a subscription purchase (iOS/Android). */
export function processPurchase(
  data: ProcessPurchaseRequest,
): Promise<PurchaseResponse> {
  return apiFetch<PurchaseResponse>('/subscription/purchase/', {
    method: 'POST',
    body: JSON.stringify(data),
  });
}

/** Cancel the current subscription. */
export function cancelSubscription(): Promise<PurchaseResponse> {
  return apiFetch<PurchaseResponse>('/subscription/cancel/', {
    method: 'POST',
  });
}

/** Restore a subscription from a previous purchase. */
export function restoreSubscription(
  data: ProcessPurchaseRequest,
): Promise<PurchaseResponse> {
  return apiFetch<PurchaseResponse>('/subscription/restore/', {
    method: 'POST',
    body: JSON.stringify(data),
  });
}

// ---------------------------------------------------------------------------
// Stripe Checkout / Portal
// ---------------------------------------------------------------------------

export interface CheckoutSessionRequest {
  price_id: string;
  success_url: string;
  cancel_url: string;
}

export interface CheckoutSessionResponse {
  checkout_url: string;
}

export interface PortalSessionRequest {
  return_url: string;
}

export interface PortalSessionResponse {
  portal_url: string;
}

/** Create a Stripe Checkout session and return the checkout URL. */
export function createCheckoutSession(
  data: CheckoutSessionRequest,
): Promise<CheckoutSessionResponse> {
  return apiFetch<CheckoutSessionResponse>('/subscription/checkout/', {
    method: 'POST',
    body: JSON.stringify(data),
  });
}

/** Create a Stripe Customer Portal session and return the portal URL. */
export function createPortalSession(
  data: PortalSessionRequest,
): Promise<PortalSessionResponse> {
  return apiFetch<PortalSessionResponse>('/subscription/portal/', {
    method: 'POST',
    body: JSON.stringify(data),
  });
}
