import Stripe from 'stripe';
import { logger } from '@/lib/logger';
import { randomUUID } from 'crypto';

if (!process.env.STRIPE_SECRET_KEY) {
  throw new Error('STRIPE_SECRET_KEY is not configured');
}

// Initialize Stripe with secret key
export const stripe = new Stripe(process.env.STRIPE_SECRET_KEY, {
  apiVersion: '2026-01-28.clover',
  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;
}) {
  if (!amount || amount <= 0) {
    throw new Error('Payment amount must be positive');
  }

  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}`,
    }, {
      idempotencyKey: `pi_${matchId}_${randomUUID()}`,
    });

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

// Create a Checkout Session for hiring a worker
export async function createCheckoutSession({
  amount,
  matchId,
  companyId,
  companyName,
  description,
  successUrl,
  cancelUrl,
  customerEmail,
}: {
  amount: number;
  matchId: string;
  companyId: string;
  companyName: string;
  description: string;
  successUrl: string;
  cancelUrl: string;
  customerEmail?: string;
}) {
  if (!amount || amount <= 0) {
    throw new Error('Payment amount must be positive');
  }

  try {
    const session = await stripe.checkout.sessions.create({
      mode: 'payment',
      payment_method_types: ['card'],
      ...(customerEmail ? { customer_email: customerEmail } : {}),
      line_items: [
        {
          price_data: {
            currency: 'aud',
            product_data: {
              name: 'RateRight Hire Fee',
              description,
              metadata: {
                gst_status: 'GST-free',
                abn: '88 688 279 769',
              },
            },
            unit_amount: Math.round(amount * 100),
          },
          quantity: 1,
        },
      ],
      // Custom text on checkout page for receipt compliance
      custom_text: {
        submit: {
          message: 'RateRight Pty Ltd | ABN 88 688 279 769 | GST-free supply',
        },
      },
      metadata: {
        match_id: matchId,
        company_id: companyId,
        company_name: companyName,
      },
      payment_intent_data: {
        metadata: {
          match_id: matchId,
          company_id: companyId,
          company_name: companyName,
          description,
        },
        ...(customerEmail ? { receipt_email: customerEmail } : {}),
      },
      success_url: successUrl,
      cancel_url: cancelUrl,
    }, {
      idempotencyKey: `cs_${matchId}_${randomUUID()}`,
    });

    return {
      sessionId: session.id,
      url: session.url,
    };
  } catch (error) {
    logger.error('Error creating Checkout Session:', error);
    throw new Error('Failed to create checkout session');
  }
}

// Retrieve a PaymentIntent
export async function retrievePaymentIntent(paymentIntentId: string) {
  try {
    return await stripe.paymentIntents.retrieve(paymentIntentId);
  } catch (error) {
    logger.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) {
    logger.error('Webhook signature verification failed:', error);
    throw new Error('Invalid webhook signature');
  }
}
