import { apiClient } from './client';

export interface Subscription {
  id: string;
  tenantId: string;
  plan: string;
  status: string;
  amount: string;
  frequency: string;
  mpPreapprovalId: string | null;
  currentPeriodStart: string | null;
  currentPeriodEnd: string | null;
  pendingPlan: string | null;
  pendingFrequency: string | null;
  pendingEffectiveAt: string | null;
  upgradePreferenceId: string | null;
  upgradeTargetPlan: string | null;
  upgradeTargetAmount: string | null;
  createdAt: string;
  updatedAt: string;
}

export interface PlanPrice {
  id: number;
  plan: string;
  frequency: 'monthly' | 'annual';
  amount: string;
  updatedAt: string;
}

export interface Payment {
  id: string;
  tenantId: string;
  subscriptionId: string | null;
  mpPaymentId: string | null;
  amount: string;
  status: string;
  paymentMethod: string | null;
  paidAt: string | null;
  createdAt: string;
}

export async function getSubscription(tenantId: string): Promise<Subscription | null> {
  try {
    const response = await apiClient.get<Subscription>(`/subscriptions/${tenantId}`);
    return response.data;
  } catch (error: any) {
    // 404 significa "no hay suscripción registrada" — no es error, es estado inicial
    if (error?.response?.status === 404) return null;
    throw error;
  }
}

type PlanFreqPayload = { plan: string; frequency: 'monthly' | 'annual' };

export async function startTrial(data: PlanFreqPayload): Promise<{ subscription: Subscription; trialEndsAt: string }> {
  const response = await apiClient.post('/subscriptions/me/trial', data);
  return response.data;
}

export async function subscribeMe(data: PlanFreqPayload): Promise<{ subscription: Subscription; paymentUrl: string }> {
  const response = await apiClient.post('/subscriptions/me/subscribe', data);
  return response.data;
}

export async function changeMyPlan(data: PlanFreqPayload): Promise<{ subscription: Subscription; effectiveAt: string }> {
  const response = await apiClient.post('/subscriptions/me/change', data);
  return response.data;
}

export async function cancelMySubscription(): Promise<{ subscription: Subscription }> {
  const response = await apiClient.post('/subscriptions/me/cancel');
  return response.data;
}

export async function upgradeMe(plan: string): Promise<{ subscription: Subscription; checkoutUrl: string; proratedAmount: number }> {
  const response = await apiClient.post('/subscriptions/me/upgrade', { plan });
  return response.data;
}

export async function cancelPendingUpgrade(): Promise<{ ok: boolean }> {
  const response = await apiClient.post('/subscriptions/me/upgrade/cancel');
  return response.data;
}

export async function reactivateMe(): Promise<{ subscription: Subscription; paymentUrl: string }> {
  const response = await apiClient.post('/subscriptions/me/reactivate');
  return response.data;
}

export async function generatePaymentLink(tenantId: string): Promise<{ paymentUrl: string }> {
  const response = await apiClient.post<{ paymentUrl: string }>(`/subscriptions/${tenantId}/generate-link`);
  return response.data;
}

export async function markAsPaid(tenantId: string, amount: number): Promise<Payment> {
  const response = await apiClient.post<Payment>(`/subscriptions/${tenantId}/mark-paid`, { amount });
  return response.data;
}

export async function getPaymentHistory(tenantId: string): Promise<Payment[]> {
  const response = await apiClient.get<Payment[]>(`/subscriptions/${tenantId}/payments`);
  return response.data;
}
