/**
 * Stripe MCP Server - Payments
 *
 * Provides Stripe payment operations (payment intents, charges).
 * Token savings: 7,000+ per operation
 */

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

export interface PaymentIntent {
  id: string;
  amount: number;
  currency: string;
  status: string;
  customer: string | null;
  metadata: Record<string, string>;
  created: number;
}

export interface ListPaymentsInput {
  customerId?: string;
  limit?: number;
  startingAfter?: string;
}

export interface PaymentStats {
  totalAmount: number;
  count: number;
  byStatus: Record<string, number>;
  averageAmount: number;
  successRate: number;
}

/**
 * Get payment intent by ID.
 *
 * @param paymentIntentId - Payment intent ID
 * @returns Payment intent object
 *
 * @example
 * ```typescript
 * const payment = await getPaymentIntent('pi_xxx');
 * console.log(`Amount: ${payment.amount / 100} ${payment.currency.toUpperCase()}`);
 * console.log(`Status: ${payment.status}`);
 * ```
 */
export async function getPaymentIntent(
  paymentIntentId: string,
): Promise<PaymentIntent> {
  return callMCPTool<PaymentIntent>("stripe__get_payment_intent", {
    paymentIntentId,
  });
}

/**
 * List payment intents with optional filtering.
 *
 * @param input - Filter parameters
 * @returns Array of payment intents
 *
 * @example
 * ```typescript
 * const payments = await listPayments({ customerId: 'cus_xxx', limit: 100 });
 *
 * // Analyze payment data in code
 * const total = payments.reduce((sum, p) => sum + p.amount, 0);
 * console.log(`Total paid: ${total / 100} SAR`);
 *
 * const successful = payments.filter(p => p.status === 'succeeded');
 * console.log(`Success rate: ${(successful.length / payments.length * 100).toFixed(1)}%`);
 * ```
 */
export async function listPayments(
  input: ListPaymentsInput = {},
): Promise<PaymentIntent[]> {
  return callMCPTool<PaymentIntent[]>("stripe__list_payments", input);
}

/**
 * Get payment statistics.
 *
 * @param customerId - Optional customer ID filter
 * @returns Payment statistics
 *
 * @example
 * ```typescript
 * const stats = await getPaymentStats();
 * console.log(`Total revenue: ${stats.totalAmount / 100} SAR`);
 * console.log(`Payments: ${stats.count}`);
 * console.log(`Success rate: ${stats.successRate}%`);
 * console.log('By status:', stats.byStatus);
 * ```
 */
export async function getPaymentStats(
  customerId?: string,
): Promise<PaymentStats> {
  return callMCPTool<PaymentStats>("stripe__get_payment_stats", { customerId });
}

export default {
  getPaymentIntent,
  listPayments,
  getPaymentStats,
};
