import Stripe from 'stripe';

if (!process.env.STRIPE_SECRET_KEY) {
  throw new Error('STRIPE_SECRET_KEY is not defined in environment variables');
}

export const stripe = new Stripe(process.env.STRIPE_SECRET_KEY, {
  // Use account default; type expects a specific literal in this project setup
  typescript: true,
  apiVersion: '2024-04-10',  // new added for " missing_payment_method: 'create_invoice'"
} as any);

// Helper function to create a payment intent
export async function  createPaymentIntent(
  amount: number,
  currency: string,
  metadata: Record<string, string> = {},
  customerId?: string,
  shipping?: Stripe.PaymentIntentCreateParams['shipping'],
  priceId?:any
): Promise<Stripe.PaymentIntent> {
  try {
    const paymentIntentParams: Stripe.PaymentIntentCreateParams = {
      amount: Math.round(amount * 100), // Convert to cents
      currency: currency.toLowerCase(),
      metadata,
      // Indian regulations compliance: export transactions require description
      description: 'Digital service - Freelancer marketplace membership subscription for professional services',
      automatic_payment_methods: {
        enabled: true,
      },
    };

    // Send receipt to the customer when we have their email
    if ((metadata as any)?.customerEmail) {
      (paymentIntentParams as any).receipt_email = (metadata as any).customerEmail;
    }

    // Add customer for Indian export regulations compliance
    if (customerId) {
      paymentIntentParams.customer = customerId;
    }

    // Include customer shipping details when available for export regulations compliance
    if (shipping) {
      paymentIntentParams.shipping = shipping;
    }

    const paymentIntent = await stripe.paymentIntents.create(paymentIntentParams);

    return paymentIntent;
  } catch (error) {
    console.error('Error creating payment intent:', error);
    throw new Error('Failed to create payment intent');
  }
}



// Helper function to payment subscription create 
export async function  createSubscriptionsIntent(
  amount: number,
  currency: string,
  metadata: Record<string, string> = {},
  customerId: string,
  shipping?: Stripe.PaymentIntentCreateParams['shipping'],
  priceId?:any
): Promise<any> {

try {
      // 2️⃣ Create subscription
    const subscription = await stripe.subscriptions.create({
      customer: customerId,
      items: [{ price: priceId }],
      payment_behavior: 'default_incomplete',
      expand: ['latest_invoice.payment_intent'],
      metadata: metadata
    });
    const clientSecret = (subscription.latest_invoice as any).payment_intent.client_secret;
    const paymentIntentGet = (subscription.latest_invoice as any).payment_intent.id;

    if (paymentIntentGet) {
      await stripe.paymentIntents.update(paymentIntentGet, { metadata });
    }

    const  paymentIntent = { id:paymentIntentGet, client_secret:clientSecret};   
    return paymentIntent;
  } catch (err: any) {
    console.log('Error creating payment intent:', err);
    throw new Error('Failed to create payment intent');
  }
}




// Helper function to confirm a payment intent
export async function confirmPaymentIntent(
  paymentIntentId: string
): Promise<Stripe.PaymentIntent> {
  try {
    const paymentIntent = await stripe.paymentIntents.confirm(paymentIntentId);
    return paymentIntent;
  } catch (error) {
    console.error('Error confirming payment intent:', error);
    throw new Error('Failed to confirm payment intent');
  }
}

// Helper function to retrieve a payment intent
export async function retrievePaymentIntent(
  paymentIntentId: string
): Promise<Stripe.PaymentIntent> {
  try {
    const paymentIntent = await stripe.paymentIntents.retrieve(paymentIntentId);
    return paymentIntent;
  } catch (error) {
    console.error('Error retrieving payment intent:', error);
    throw new Error('Failed to retrieve payment intent');
  }
}

// Helper function to create a customer
export async function createCustomer(
  email: string,
  name?: string,
  metadata: Record<string, string> = {},
  address?: Stripe.AddressParam
): Promise<Stripe.Customer> {
  try {
    const customer = await stripe.customers.create({
      email,
      name,
      address,
      metadata,
    });

    return customer;
  } catch (error) {
    console.error('Error creating customer:', error);
    throw new Error('Failed to create customer');
  }
}

// Helper function to retrieve a customer by email
export async function findCustomerByEmail(email: string): Promise<Stripe.Customer | null> {
  try {
    const customers = await stripe.customers.list({
      email,
      limit: 1,
    });

    return customers.data.length > 0 ? customers.data[0] : null;
  } catch (error) {
    console.error('Error finding customer:', error);
    return null;
  }
}

// Helper function to create a subscription (for future use)
export async function createSubscription(
  customerId: string,
  priceId: string,
  metadata: Record<string, string> = {}
): Promise<Stripe.Subscription> {
  try {
    const subscription = await stripe.subscriptions.create({
      customer: customerId,
      items: [{ price: priceId }],
      metadata,
    });

    return subscription;
  } catch (error) {
    console.error('Error creating subscription:', error);
    throw new Error('Failed to create subscription');
  }
}

// Helper to convert Stripe payment status to our database status
export function mapStripeStatusToPaymentStatus(status: Stripe.PaymentIntent.Status): 'PENDING' | 'COMPLETED' | 'FAILED' | 'REFUNDED' {
  switch (status) {
    case 'succeeded':
      return 'COMPLETED';
    case 'processing':
    case 'requires_payment_method':
    case 'requires_confirmation':
    case 'requires_action':
      return 'PENDING';
    case 'canceled':
    case 'requires_capture':
      return 'FAILED';
    default:
      return 'PENDING';
  }
}

export default stripe;