// Create a new file called userOrders.js in the routes directory

const express = require('express');
const router = express.Router();

module.exports = (pool, query, authMiddleware) => {
  // Apply authentication middleware to all routes
  router.use(authMiddleware);
  
  // Get all orders for the authenticated user
  router.get('/', async (req, res, next) => {
    try {
      const userId = req.user.id;
      
      // Get orders with basic information
      const result = await query(`
        SELECT 
          o.id,
          o.status,
          o.total_amount,
          o.shipping_address,
          o.created_at,
          o.updated_at,
          o.payment_completed,
          o.shipping_date,
          COUNT(oi.id) AS item_count,
          CASE WHEN o.shipping_info IS NOT NULL THEN true ELSE false END AS has_shipping_info,
          (SELECT SUM(quantity) FROM order_items WHERE order_id = o.id) AS total_items
        FROM orders o
        LEFT JOIN order_items oi ON o.id = oi.order_id
        WHERE o.user_id = $1
        GROUP BY o.id
        ORDER BY o.created_at DESC
      `, [userId]);
      
      res.json(result.rows);
    } catch (error) {
      next(error);
    }
  });
  
  // Get a single order with details for the authenticated user
  router.get('/:id', async (req, res, next) => {
    try {
      const { id } = req.params;
      const userId = req.user.id;
      
      // Get order with verification that it belongs to the current user
      const orderResult = await query(`
        SELECT o.*
        FROM orders o
        WHERE o.id = $1 AND o.user_id = $2
      `, [id, userId]);
      
      if (orderResult.rows.length === 0) {
        return res.status(404).json({
          error: true,
          message: 'Order not found'
        });
      }
      
      // Get order items with product details
      const itemsResult = await query(`
        SELECT 
          oi.id, 
          oi.product_id,
          oi.quantity, 
          oi.price_at_purchase,
          p.name as product_name,
          p.description as product_description,
          pc.name as product_category,
          (
            SELECT json_agg(
              json_build_object(
                'id', pi.id,
                'path', pi.image_path,
                'isPrimary', pi.is_primary,
                'displayOrder', pi.display_order
              ) ORDER BY pi.display_order
            )
            FROM product_images pi
            WHERE pi.product_id = p.id
          ) AS product_images
        FROM order_items oi
        JOIN products p ON oi.product_id = p.id
        JOIN product_categories pc ON p.category_id = pc.id
        WHERE oi.order_id = $1
      `, [id]);
      
      // Combine order with items
      const order = {
        ...orderResult.rows[0],
        items: itemsResult.rows
      };
      
      res.json(order);
    } catch (error) {
      next(error);
    }
  });
  
  return router;
};