/**
 * Stripe Customers Module
 *
 * Handles customer management in Stripe.
 */

import Stripe from 'stripe';
import { stripe } from './client';
import { logger } from '@/lib/logger';

// =============================================================================
// Customer Management
// =============================================================================

/**
 * Create a customer
 */
export async function createCustomer(
  params: Stripe.CustomerCreateParams
): Promise<Stripe.Customer> {
  try {
    const customer = await stripe.customers.create(params);
    return customer;
  } catch (error) {
    logger.error('Error creating customer', error);
    throw error;
  }
}

/**
 * Retrieve a customer by ID
 */
export async function getCustomer(customerId: string): Promise<Stripe.Customer | null> {
  try {
    const customer = await stripe.customers.retrieve(customerId);
    return customer as Stripe.Customer;
  } catch (error) {
    logger.error('Error retrieving customer', error);
    return null;
  }
}

/**
 * Get or create a customer by email
 * Prevents duplicate customer creation
 */
export async function getOrCreateCustomer(params: {
  email: string;
  name?: string;
  metadata?: Record<string, string>;
}): Promise<Stripe.Customer> {
  try {
    // Check if customer already exists
    const existingCustomers = await stripe.customers.list({
      email: params.email,
      limit: 1,
    });

    if (existingCustomers.data.length > 0) {
      return existingCustomers.data[0];
    }

    // Create new customer
    return await createCustomer({
      email: params.email,
      name: params.name,
      metadata: params.metadata,
    });
  } catch (error) {
    logger.error('Error getting or creating customer', error);
    throw error;
  }
}

/**
 * Create a payment intent
 */
export async function createPaymentIntent(
  params: Stripe.PaymentIntentCreateParams
): Promise<Stripe.PaymentIntent> {
  try {
    const paymentIntent = await stripe.paymentIntents.create(params);
    return paymentIntent;
  } catch (error) {
    logger.error('Error creating payment intent', error);
    throw error;
  }
}
