import Stripe from 'stripe';

// Initialize Stripe with secret key
export const stripe = new Stripe(process.env.STRIPE_SECRET_KEY || '', {
  apiVersion: '2026-01-28.clover', // Use latest API version
  typescript: true,
});

// Validate Stripe is configured
export function validateStripeConfig(): void {
  if (!process.env.STRIPE_SECRET_KEY) {
    throw new Error('STRIPE_SECRET_KEY is not configured');
  }
  if (!process.env.STRIPE_WEBHOOK_SECRET) {
    throw new Error('STRIPE_WEBHOOK_SECRET is not configured');
  }
}

// Create a PaymentIntent for hiring a worker
export async function createPaymentIntent({
  amount,
  matchId,
  companyId,
  companyName,
  description,
}: {
  amount: number;
  matchId: string;
  companyId: string;
  companyName: string;
  description: string;
}) {
  try {
    const paymentIntent = await stripe.paymentIntents.create({
      amount: Math.round(amount * 100), // Convert to cents
      currency: 'aud',
      automatic_payment_methods: {
        enabled: true,
      },
      metadata: {
        match_id: matchId,
        company_id: companyId,
        company_name: companyName,
        description,
      },
      description: `RateRight Hire Fee - ${description}`,
    });

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

// Retrieve a PaymentIntent
export async function retrievePaymentIntent(paymentIntentId: string) {
  try {
    return await stripe.paymentIntents.retrieve(paymentIntentId);
  } catch (error) {
    console.error('Error retrieving PaymentIntent:', error);
    throw new Error('Failed to retrieve payment intent');
  }
}

// Construct webhook event with signature verification
export function constructWebhookEvent(
  payload: string | Buffer,
  signature: string
): Stripe.Event {
  const webhookSecret = process.env.STRIPE_WEBHOOK_SECRET;
  
  if (!webhookSecret) {
    throw new Error('STRIPE_WEBHOOK_SECRET is not configured');
  }

  try {
    return stripe.webhooks.constructEvent(payload, signature, webhookSecret);
  } catch (error) {
    console.error('Webhook signature verification failed:', error);
    throw new Error('Invalid webhook signature');
  }
}
