import api, { ApiResponse } 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 AdminSubscription {
  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;
  user: {
    id: string;
    email: string;
    agentProfile: {
      firstName: string | null;
      lastName: string | null;
    } | null;
  };
}

export interface SubscriptionsListResponse {
  data: AdminSubscription[];
  total: number;
  page: number;
  limit: number;
  totalPages: number;
}

export interface RevenueStats {
  activeSubscriptions: number;
  totalRevenue: number;
  monthlyRevenue: number;
}

class AdminStripeService {
  async getAllSubscriptions(params?: {
    status?: string;
    page?: number;
    limit?: number;
  }): Promise<SubscriptionsListResponse> {
    const queryParams = new URLSearchParams();
    if (params?.status) queryParams.set('status', params.status);
    if (params?.page) queryParams.set('page', params.page.toString());
    if (params?.limit) queryParams.set('limit', params.limit.toString());

    const response = await api.get<ApiResponse<SubscriptionsListResponse>>(
      `/stripe/admin/subscriptions?${queryParams.toString()}`,
    );
    return response.data.data;
  }

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

  async getRevenueStats(): Promise<RevenueStats> {
    const response = await api.get<ApiResponse<RevenueStats>>('/stripe/admin/stats');
    return response.data.data;
  }
}

export const adminStripeService = new AdminStripeService();
