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

/**
 * Middleware to verify JWT token
 */
function authMiddleware(req, res, next) {
  const authHeader = req.headers.authorization;
  if (!authHeader || !authHeader.startsWith('Bearer ')) {
    return res.status(401).json({ error: 'No token provided' });
  }

  try {
    const token = authHeader.split(' ')[1];
    req.user = jwt.verify(token, process.env.JWT_SECRET);
    next();
  } catch (err) {
    return res.status(401).json({ error: 'Invalid token' });
  }
}

// Apply auth middleware to all routes
router.use(authMiddleware);

/**
 * GET /api/orders
 * Lists orders for current user
 */
router.get('/', async (req, res) => {
  try {
    const userId = req.user.userId;

    // Get orders first
    const { data: orders, error } = await supabase
      .from('orders')
      .select('id, order_number, status, total_amount, currency, items, tracking_number, carrier, shipped_at, delivered_at, created_at, beneficiary_id')
      .eq('user_id', userId)
      .order('created_at', { ascending: false });

    if (error) {
      console.error('List orders error:', error);
      return res.status(500).json({ error: 'Failed to list orders' });
    }

    // Get beneficiary details for each order
    const result = [];
    for (const order of (orders || [])) {
      let beneficiary = null;
      if (order.beneficiary_id) {
        const { data: ben } = await supabase
          .from('users')
          .select('id, first_name, last_name')
          .eq('id', order.beneficiary_id)
          .single();
        if (ben) {
          beneficiary = {
            id: ben.id,
            firstName: ben.first_name,
            lastName: ben.last_name
          };
        }
      }

      result.push({
        id: order.id,
        orderNumber: order.order_number,
        status: order.status,
        totalAmount: order.total_amount,
        currency: order.currency,
        items: order.items,
        tracking: order.tracking_number ? {
          number: order.tracking_number,
          carrier: order.carrier
        } : null,
        shippedAt: order.shipped_at,
        deliveredAt: order.delivered_at,
        createdAt: order.created_at,
        beneficiary
      });
    }

    res.json({ orders: result });

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

/**
 * GET /api/orders/:id
 * Returns order details
 */
router.get('/:id', async (req, res) => {
  try {
    const userId = req.user.userId;
    const orderId = parseInt(req.params.id, 10);

    const { data: order, error } = await supabase
      .from('orders')
      .select('*')
      .eq('id', orderId)
      .eq('user_id', userId)
      .single();

    if (error || !order) {
      return res.status(404).json({ error: 'Order not found' });
    }

    // Get beneficiary details if exists
    let beneficiary = null;
    if (order.beneficiary_id) {
      const { data: ben } = await supabase
        .from('users')
        .select('id, first_name, last_name, phone, address_street, address_city, address_zip, address_state, address_country')
        .eq('id', order.beneficiary_id)
        .single();
      if (ben) {
        beneficiary = {
          id: ben.id,
          firstName: ben.first_name,
          lastName: ben.last_name,
          phone: ben.phone,
          address: {
            street: ben.address_street,
            city: ben.address_city,
            zip: ben.address_zip,
            state: ben.address_state,
            country: ben.address_country
          }
        };
      }
    }

    res.json({
      id: order.id,
      orderNumber: order.order_number,
      status: order.status,
      subtotal: order.subtotal,
      shippingCost: order.shipping_cost,
      tax: order.tax,
      totalAmount: order.total_amount,
      currency: order.currency,
      items: order.items,
      shippingAddress: order.shipping_address,
      shippingMethod: order.shipping_method,
      tracking: order.tracking_number ? {
        number: order.tracking_number,
        carrier: order.carrier
      } : null,
      paidAt: order.paid_at,
      shippedAt: order.shipped_at,
      deliveredAt: order.delivered_at,
      notes: order.notes,
      createdAt: order.created_at,
      beneficiary
    });

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

module.exports = router;
