/**
 * API MCP Server - Stripe
 *
 * Provides Stripe payment API operations (checkout, webhooks).
 * Token savings: 6,000+ per operation
 */

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

export interface CreateCheckoutInput {
  priceId: string;
  userId: string;
  successUrl: string;
  cancelUrl: string;
  metadata?: Record<string, string>;
}

export interface CheckoutResponse {
  success: boolean;
  sessionId?: string;
  url?: string;
  error?: string;
}

export interface WebhookEvent {
  id: string;
  type: string;
  data: any;
  created: number;
}

/**
 * Create Stripe checkout session.
 *
 * @param input - Checkout session parameters
 * @returns Checkout session with URL
 *
 * @example
 * ```typescript
 * const session = await createCheckoutSession({
 *   priceId: 'price_xxx',
 *   userId: 'user_123',
 *   successUrl: 'https://example.com/success',
 *   cancelUrl: 'https://example.com/cancel'
 * });
 *
 * if (session.success) {
 *   console.log(`✓ Checkout created: ${session.url}`);
 * }
 * ```
 */
export async function createCheckoutSession(
  input: CreateCheckoutInput,
): Promise<CheckoutResponse> {
  return callMCPTool<CheckoutResponse>("api__create_checkout_session", input);
}

/**
 * Test Stripe webhook processing.
 *
 * @param event - Webhook event data
 * @returns Processing result
 *
 * @example
 * ```typescript
 * const result = await testWebhook({
 *   id: 'evt_xxx',
 *   type: 'checkout.session.completed',
 *   data: { ... },
 *   created: Date.now()
 * });
 *
 * console.log(result.success ? '✓ Webhook processed' : '✗ Processing failed');
 * ```
 */
export async function testWebhook(
  event: WebhookEvent,
): Promise<{ success: boolean; message: string }> {
  return callMCPTool("api__test_stripe_webhook", event);
}

/**
 * Test complete payment flow (checkout → webhook → subscription).
 *
 * @param userId - User ID to test with
 * @param priceId - Stripe price ID
 * @returns Flow test results
 *
 * @example
 * ```typescript
 * const flow = await testPaymentFlow('user_123', 'price_xxx');
 *
 * console.log('Payment Flow:');
 * console.log(`  Checkout: ${flow.checkout.success ? '✓' : '✗'}`);
 * console.log(`  Webhook: ${flow.webhook.success ? '✓' : '✗'}`);
 * console.log(`  Subscription: ${flow.subscription ? '✓' : '✗'}`);
 * ```
 */
export async function testPaymentFlow(
  userId: string,
  priceId: string,
): Promise<{
  checkout: CheckoutResponse;
  webhook: { success: boolean };
  subscription: boolean;
}> {
  return callMCPTool("api__test_payment_flow", { userId, priceId });
}

export default {
  createCheckoutSession,
  testWebhook,
  testPaymentFlow,
};
