/**
 * Fiat Onramp Service
 * Allows users to buy crypto with credit card via Stripe
 * 
 * Setup: Already have STRIPE_SECRET_KEY in .env
 */
'use strict';
require('dotenv').config();

const stripe = require('stripe')(process.env.STRIPE_SECRET_KEY);
const { createClient } = require('@supabase/supabase-js');
const supabase = createClient(process.env.SUPABASE_URL, process.env.SUPABASE_SERVICE_KEY);

const CONVERSION_RATE = 100; // 1 USD = 100 VAE (Ⓥ)

const fiatOnramp = {
  // Create checkout session for deposit
  async createCheckout(userId, amountUSD, successUrl, cancelUrl) {
    const session = await stripe.checkout.sessions.create({
      payment_method_types: ['card'],
      line_items: [{
        price_data: {
          currency: 'usd',
          product_data: {
            name: 'Loopuman Credits',
            description: `Ⓥ${amountUSD * CONVERSION_RATE} platform credits`,
          },
          unit_amount: amountUSD * 100, // Stripe uses cents
        },
        quantity: 1,
      }],
      mode: 'payment',
      success_url: successUrl,
      cancel_url: cancelUrl,
      metadata: { userId, amountVAE: amountUSD * CONVERSION_RATE },
    });
    return session;
  },

  // Handle successful payment webhook
  async handlePaymentSuccess(session) {
    const { userId, amountVAE } = session.metadata;
    
    // Credit user balance
    const { data: bal } = await supabase.from('vae_balances')
      .select('available')
      .eq('user_id', userId)
      .single();
    
    await supabase.from('vae_balances').update({
      available: (bal?.available || 0) + parseInt(amountVAE)
    }).eq('user_id', userId);

    // Record transaction
    await supabase.from('transactions').insert({
      user_id: userId,
      type: 'fiat_deposit',
      amount: parseInt(amountVAE),
      description: `Card deposit: $${amountVAE / CONVERSION_RATE}`,
      metadata: { stripe_session: session.id }
    });

    return { success: true, credited: amountVAE };
  },

  // Get deposit options
  getOptions() {
    return [
      { usd: 5, vae: 500, label: '$5 → Ⓥ500' },
      { usd: 10, vae: 1000, label: '$10 → Ⓥ1,000' },
      { usd: 25, vae: 2500, label: '$25 → Ⓥ2,500' },
      { usd: 50, vae: 5000, label: '$50 → Ⓥ5,000' },
      { usd: 100, vae: 10000, label: '$100 → Ⓥ10,000' },
    ];
  }
};

module.exports = fiatOnramp;
