import { apiClient } from './api-client';

export interface PlanDto {
  id: string;
  tier: string;
  name: string;
  priceMonthlyVND: string;
  priceYearlyVND: string;
  maxListings: number;
  maxSavedSearches: number;
  features: Record<string, boolean | number | string>;
  isActive: boolean;
}

export interface SubscriptionInfo {
  id: string;
  planTier: string;
  status: string;
  currentPeriodStart: string;
  currentPeriodEnd: string;
  cancelledAt: string | null;
  createdAt: string;
}

export interface BillingHistoryDto {
  subscription: SubscriptionInfo | null;
  payments: Array<{
    id: string;
    provider: string;
    type: string;
    amountVND: string;
    status: string;
    createdAt: string;
  }>;
  total: number;
}

export interface QuotaCheckResult {
  metric: string;
  used: number;
  limit: number;
  remaining: number;
}

export interface CreateSubscriptionResult {
  subscriptionId: string;
  planTier: string;
  status: string;
  currentPeriodStart: string;
  currentPeriodEnd: string;
}

export const subscriptionApi = {
  getPlans: () => apiClient.get<PlanDto[]>('/subscriptions/plans'),

  getPlanByTier: (tier: string) =>
    apiClient.get<PlanDto>(`/subscriptions/plans/${tier}`),

  getBillingHistory: (limit = 20, offset = 0) =>
    apiClient.get<BillingHistoryDto>(
      `/subscriptions/billing?limit=${limit}&offset=${offset}`,
    ),

  checkQuota: (metric: string) =>
    apiClient.get<QuotaCheckResult>(`/subscriptions/quota/${metric}`),

  createSubscription: (planTier: string, billingCycle: 'monthly' | 'yearly') =>
    apiClient.post<CreateSubscriptionResult>('/subscriptions', {
      planTier,
      billingCycle,
    }),

  upgradeSubscription: (newPlanTier: string) =>
    apiClient.post<{ message: string }>('/subscriptions/upgrade', {
      newPlanTier,
    }),

  cancelSubscription: (_reason: string) =>
    apiClient.delete<{ message: string }>('/subscriptions'),
};
