import api from './api';

export interface SubscriptionPlan {
  id: string;
  name: string;
  description: string | null;
  stripePriceId: string;
  amount: number;
  currency: string;
  interval: string;
  features: string | null;
  isActive: boolean;
  sortOrder: number;
}

export interface AgentSubscription {
  id: string;
  userId: string;
  planId: string;
  stripeCustomerId: string;
  stripeSubscriptionId: string | null;
  status: string;
  currentPeriodStart: string | null;
  currentPeriodEnd: string | null;
  cancelAtPeriodEnd: boolean;
  canceledAt: string | null;
  createdAt: string;
  plan: SubscriptionPlan;
}

export interface PaymentRecord {
  id: string;
  subscriptionId: string | null;
  userId: string;
  stripePaymentIntentId: string | null;
  stripeInvoiceId: string | null;
  amount: number;
  currency: string;
  status: string;
  receiptUrl: string | null;
  createdAt: string;
  subscription: AgentSubscription | null;
}

class StripeApiService {
  async getPlans(): Promise<SubscriptionPlan[]> {
    const response = await api.get('/stripe/plans');
    return response.data.data;
  }

  async getSubscription(): Promise<AgentSubscription | null> {
    const response = await api.get('/stripe/subscription');
    return response.data.data;
  }

  async createCheckoutSession(planId: string): Promise<{ url: string }> {
    const response = await api.post('/stripe/create-checkout-session', { planId });
    return response.data.data;
  }

  async createPortalSession(): Promise<{ url: string }> {
    const response = await api.post('/stripe/create-portal-session', {});
    return response.data.data;
  }

  async cancelSubscription(): Promise<AgentSubscription> {
    const response = await api.post('/stripe/cancel-subscription');
    return response.data.data;
  }

  async getPaymentHistory(): Promise<PaymentRecord[]> {
    const response = await api.get('/stripe/payments');
    return response.data.data;
  }
}

export const stripeService = new StripeApiService();
