/**
 * Database MCP Server - Subscriptions
 *
 * Provides subscription management operations.
 * Integrates with Stripe subscription data stored in Prisma.
 * Token savings: 8,000+ per operation
 */

import { callMCPTool } from "../../client.js";

export interface Subscription {
  id: string;
  userId: string;
  stripeSubscriptionId: string;
  stripePriceId: string;
  stripeCustomerId: string;
  status: string;
  currentPeriodStart: Date;
  currentPeriodEnd: Date;
  cancelAtPeriodEnd: boolean;
  createdAt: Date;
  updatedAt: Date;
}

export interface GetSubscriptionsInput {
  userId?: string;
  status?: string;
  limit?: number;
  offset?: number;
}

export interface SubscriptionStats {
  total: number;
  active: number;
  cancelled: number;
  pastDue: number;
  trialing: number;
  byPriceId: Record<string, number>;
  revenue: {
    monthly: number;
    annual: number;
  };
}

/**
 * Get subscriptions from the database.
 *
 * @param input - Query parameters
 * @returns Array of subscription objects
 *
 * @example
 * ```typescript
 * // Get all active subscriptions
 * const active = await getSubscriptions({ status: 'active' });
 *
 * // Get user's subscriptions
 * const userSubs = await getSubscriptions({ userId: 'user_123' });
 *
 * // Analyze subscription distribution
 * const all = await getSubscriptions({ limit: 1000 });
 * const byPlan = all.reduce((acc, s) => {
 *   acc[s.stripePriceId] = (acc[s.stripePriceId] || 0) + 1;
 *   return acc;
 * }, {});
 * console.log('Subscriptions by plan:', byPlan);
 * ```
 */
export async function getSubscriptions(
  input: GetSubscriptionsInput = {},
): Promise<Subscription[]> {
  return callMCPTool<Subscription[]>("database__get_subscriptions", input);
}

/**
 * Get subscription by Stripe subscription ID.
 *
 * @param stripeSubscriptionId - Stripe subscription ID
 * @returns Subscription object or null
 *
 * @example
 * ```typescript
 * const sub = await getSubscriptionByStripeId('sub_xxx');
 * if (sub) {
 *   console.log(`Status: ${sub.status}`);
 *   console.log(`Period: ${sub.currentPeriodStart} - ${sub.currentPeriodEnd}`);
 * }
 * ```
 */
export async function getSubscriptionByStripeId(
  stripeSubscriptionId: string,
): Promise<Subscription | null> {
  return callMCPTool<Subscription | null>(
    "database__get_subscription_by_stripe_id",
    { stripeSubscriptionId },
  );
}

/**
 * Get subscription statistics and revenue metrics.
 *
 * @returns Subscription stats with revenue data
 *
 * @example
 * ```typescript
 * const stats = await getSubscriptionStats();
 * console.log(`Active: ${stats.active}/${stats.total}`);
 * console.log(`MRR: $${stats.revenue.monthly}`);
 * console.log(`ARR: $${stats.revenue.annual}`);
 * console.log('Plan distribution:', stats.byPriceId);
 * ```
 */
export async function getSubscriptionStats(): Promise<SubscriptionStats> {
  return callMCPTool<SubscriptionStats>("database__get_subscription_stats", {});
}

/**
 * Get user's active subscription.
 *
 * @param userId - User ID
 * @returns Active subscription or null
 *
 * @example
 * ```typescript
 * const sub = await getUserActiveSubscription('user_123');
 * if (sub) {
 *   console.log('User has active subscription');
 *   console.log(`Renews: ${sub.currentPeriodEnd}`);
 * } else {
 *   console.log('No active subscription');
 * }
 * ```
 */
export async function getUserActiveSubscription(
  userId: string,
): Promise<Subscription | null> {
  return callMCPTool<Subscription | null>(
    "database__get_user_active_subscription",
    { userId },
  );
}

export default {
  getSubscriptions,
  getSubscriptionByStripeId,
  getSubscriptionStats,
  getUserActiveSubscription,
};
