const express = require('express');
const router = express.Router();
const Stripe = require('stripe');
const { supabase } = require('../config/supabase');

const stripe = new Stripe(process.env.STRIPE_SECRET_KEY);

/**
 * POST /api/stripe/create-checkout-session
 * Creates a Stripe Checkout session for purchasing Starter Kit + optional Premium subscription
 */
router.post('/create-checkout-session', async (req, res) => {
  try {
    const {
      userId,
      beneficiaryName,
      beneficiaryAddress,
      beneficiaryPhone,
      beneficiaryNotes,
      shippingAddress,
      includePremium = true
    } = req.body;

    if (!userId) {
      return res.status(400).json({ error: 'userId is required' });
    }

    if (!beneficiaryName || !beneficiaryAddress) {
      return res.status(400).json({ error: 'Beneficiary name and address are required' });
    }

    // Build line items
    const lineItems = [
      {
        price: process.env.STRIPE_PRICE_STARTER_KIT,
        quantity: 1,
      }
    ];

    if (includePremium) {
      lineItems.push({
        price: process.env.STRIPE_PRICE_PREMIUM,
        quantity: 1,
      });
    }

    // Create checkout session
    const sessionConfig = {
      mode: includePremium ? 'subscription' : 'payment',
      payment_method_types: ['card'],
      line_items: lineItems,
      success_url: `${process.env.FRONTEND_URL}/checkout/success?session_id={CHECKOUT_SESSION_ID}`,
      cancel_url: `${process.env.FRONTEND_URL}/checkout/cancel`,
      customer_email: req.body.email,
      metadata: {
        userId,
        beneficiaryName,
        beneficiaryAddress,
        beneficiaryPhone: beneficiaryPhone || '',
        beneficiaryNotes: beneficiaryNotes || '',
        shippingAddress: JSON.stringify(shippingAddress),
        includePremium: includePremium ? 'true' : 'false'
      },
      shipping_address_collection: {
        allowed_countries: ['US', 'CA']
      }
    };

    // Only add shipping options for payment mode (not subscription)
    if (!includePremium) {
      sessionConfig.shipping_options = [
        {
          shipping_rate_data: {
            type: 'fixed_amount',
            fixed_amount: { amount: 0, currency: 'usd' },
            display_name: 'Standard shipping',
            delivery_estimate: {
              minimum: { unit: 'business_day', value: 5 },
              maximum: { unit: 'business_day', value: 7 },
            },
          },
        },
        {
          shipping_rate_data: {
            type: 'fixed_amount',
            fixed_amount: { amount: 1500, currency: 'usd' },
            display_name: 'Express shipping',
            delivery_estimate: {
              minimum: { unit: 'business_day', value: 2 },
              maximum: { unit: 'business_day', value: 3 },
            },
          },
        },
      ];
    }

    const session = await stripe.checkout.sessions.create(sessionConfig);

    res.json({
      sessionId: session.id,
      url: session.url
    });

  } catch (error) {
    console.error('Checkout session error:', error);
    res.status(500).json({ error: error.message });
  }
});

/**
 * POST /api/stripe/create-portal-session
 * Creates a Stripe Customer Portal session for managing subscriptions
 */
router.post('/create-portal-session', async (req, res) => {
  try {
    const { customerId } = req.body;

    if (!customerId) {
      return res.status(400).json({ error: 'customerId is required' });
    }

    const session = await stripe.billingPortal.sessions.create({
      customer: customerId,
      return_url: `${process.env.FRONTEND_URL}/settings`,
    });

    res.json({ url: session.url });

  } catch (error) {
    console.error('Portal session error:', error);
    res.status(500).json({ error: error.message });
  }
});

/**
 * GET /api/stripe/products
 * Returns available products and prices for the frontend
 */
router.get('/products', async (req, res) => {
  try {
    res.json({
      starterKit: {
        name: 'WellNuo Starter Kit',
        description: '2x Motion Sensors + 1x Door Sensor + 1x Hub',
        price: 249.00,
        priceId: process.env.STRIPE_PRICE_STARTER_KIT
      },
      premium: {
        name: 'WellNuo Premium',
        description: 'AI Julia assistant, 90-day history, invite up to 5 family members',
        price: 9.99,
        interval: 'month',
        priceId: process.env.STRIPE_PRICE_PREMIUM
      }
    });
  } catch (error) {
    res.status(500).json({ error: error.message });
  }
});

/**
 * GET /api/stripe/session/:sessionId
 * Get checkout session details (for success page)
 */
router.get('/session/:sessionId', async (req, res) => {
  try {
    const session = await stripe.checkout.sessions.retrieve(req.params.sessionId, {
      expand: ['line_items', 'customer', 'subscription']
    });

    res.json({
      id: session.id,
      status: session.status,
      paymentStatus: session.payment_status,
      customerEmail: session.customer_email,
      amountTotal: session.amount_total / 100,
      metadata: session.metadata
    });

  } catch (error) {
    console.error('Get session error:', error);
    res.status(500).json({ error: error.message });
  }
});

module.exports = router;
