/**
 * Admin Order Management Routes
 * Handles both regular orders and package orders
 */

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

/**
 * GET /api/admin/orders
 * List all orders with pagination and filtering
 */
router.get('/orders', async (req, res) => {
  try {
    const pool = req.app.locals.pool;
    const { page = 1, limit = 20, search = '', status = '', user_id = '' } = req.query;
    const offset = (page - 1) * limit;

    // Build WHERE clause
    let whereConditions = ['1=1'];
    let params = [];

    if (search) {
      whereConditions.push(`(o.id LIKE ? OR u.email LIKE ? OR u.first_name LIKE ? OR u.last_name LIKE ?)`);
      const searchParam = `%${search}%`;
      params.push(searchParam, searchParam, searchParam, searchParam);
    }

    if (status) {
      whereConditions.push(`o.status = ?`);
      params.push(status);
    }

    if (user_id) {
      whereConditions.push(`o.user_id = ?`);
      params.push(user_id);
    }

    const whereClause = `WHERE ${whereConditions.join(' AND ')}`;

    // Get total count
    const [countResult] = await pool.execute(
      `SELECT COUNT(*) as total FROM orders o ${whereClause}`,
      params
    );
    const total = countResult[0].total;

    // Get orders with user and service details
    const [orders] = await pool.execute(
      `SELECT
        o.id,
        o.user_id,
        o.service_id,
        o.link,
        o.quantity,
        o.price,
        o.start_count,
        o.remain_count,
        o.status,
        o.api_order_id,
        o.created_at,
        o.updated_at,
        u.email as user_email,
        u.first_name as user_first_name,
        u.last_name as user_last_name,
        s.name as service_name,
        c.name as category_name
      FROM orders o
      LEFT JOIN users u ON o.user_id = u.id
      LEFT JOIN services s ON o.service_id = s.id
      LEFT JOIN categories c ON s.category_id = c.id
      ${whereClause}
      ORDER BY o.created_at DESC
      LIMIT ? OFFSET ?`,
      [...params, parseInt(limit), parseInt(offset)]
    );

    res.json({
      success: true,
      orders: orders.map(order => ({
        ...order,
        user_name: `${order.user_first_name || ''} ${order.user_last_name || ''}`.trim() || order.user_email
      })),
      pagination: {
        page: parseInt(page),
        limit: parseInt(limit),
        total,
        pages: Math.ceil(total / limit)
      }
    });
  } catch (error) {
    console.error('[Admin Orders] Error listing orders:', error);
    res.status(500).json({
      success: false,
      error: 'Failed to list orders',
      message: error.message
    });
  }
});

/**
 * GET /api/admin/orders/:id
 * Get order details
 */
router.get('/orders/:id', async (req, res) => {
  try {
    const pool = req.app.locals.pool;
    const { id } = req.params;

    const [orders] = await pool.execute(
      `SELECT
        o.*,
        u.email as user_email,
        u.first_name as user_first_name,
        u.last_name as user_last_name,
        u.balance as user_balance,
        s.name as service_name,
        s.description as service_description,
        c.name as category_name,
        p.name as provider_name
      FROM orders o
      LEFT JOIN users u ON o.user_id = u.id
      LEFT JOIN services s ON o.service_id = s.id
      LEFT JOIN categories c ON s.category_id = c.id
      LEFT JOIN api_providers p ON s.api_provider_id = p.id
      WHERE o.id = ?`,
      [id]
    );

    if (orders.length === 0) {
      return res.status(404).json({
        success: false,
        error: 'Order not found'
      });
    }

    res.json({
      success: true,
      order: orders[0]
    });
  } catch (error) {
    console.error('[Admin Orders] Error getting order:', error);
    res.status(500).json({
      success: false,
      error: 'Failed to get order details',
      message: error.message
    });
  }
});

/**
 * PUT /api/admin/orders/:id/status
 * Update order status
 */
router.put('/orders/:id/status', async (req, res) => {
  try {
    const pool = req.app.locals.pool;
    const { id } = req.params;
    const { status } = req.body;

    const validStatuses = ['pending', 'processing', 'completed', 'partial', 'canceled', 'failed'];
    if (!validStatuses.includes(status)) {
      return res.status(400).json({
        success: false,
        error: 'Invalid status',
        message: `Status must be one of: ${validStatuses.join(', ')}`
      });
    }

    const [result] = await pool.execute(
      `UPDATE orders SET status = ?, updated_at = NOW() WHERE id = ?`,
      [status, id]
    );

    if (result.affectedRows === 0) {
      return res.status(404).json({
        success: false,
        error: 'Order not found'
      });
    }

    res.json({
      success: true,
      message: `Order status updated to ${status}`
    });
  } catch (error) {
    console.error('[Admin Orders] Error updating status:', error);
    res.status(500).json({
      success: false,
      error: 'Failed to update order status',
      message: error.message
    });
  }
});

/**
 * GET /api/admin/orders/stats
 * Get order statistics
 */
router.get('/orders-stats', async (req, res) => {
  try {
    const pool = req.app.locals.pool;

    const [stats] = await pool.execute(`
      SELECT
        COUNT(*) as total_orders,
        SUM(CASE WHEN status = 'pending' THEN 1 ELSE 0 END) as pending,
        SUM(CASE WHEN status = 'processing' THEN 1 ELSE 0 END) as processing,
        SUM(CASE WHEN status = 'completed' THEN 1 ELSE 0 END) as completed,
        SUM(CASE WHEN status = 'partial' THEN 1 ELSE 0 END) as partial,
        SUM(CASE WHEN status = 'canceled' THEN 1 ELSE 0 END) as canceled,
        SUM(CASE WHEN status = 'failed' THEN 1 ELSE 0 END) as failed,
        SUM(price) as total_revenue,
        SUM(CASE WHEN DATE(created_at) = CURDATE() THEN 1 ELSE 0 END) as today_orders,
        SUM(CASE WHEN DATE(created_at) = CURDATE() THEN price ELSE 0 END) as today_revenue
      FROM orders
    `);

    res.json({
      success: true,
      stats: stats[0]
    });
  } catch (error) {
    console.error('[Admin Orders] Error getting stats:', error);
    res.status(500).json({
      success: false,
      error: 'Failed to get order statistics',
      message: error.message
    });
  }
});

/**
 * DELETE /api/admin/orders/:id
 * Delete an order (admin only, use with caution)
 */
router.delete('/orders/:id', async (req, res) => {
  try {
    const pool = req.app.locals.pool;
    const { id } = req.params;

    // Check if order exists
    const [existing] = await pool.execute(
      `SELECT id, status, user_id, price FROM orders WHERE id = ?`,
      [id]
    );

    if (existing.length === 0) {
      return res.status(404).json({
        success: false,
        error: 'Order not found'
      });
    }

    const order = existing[0];

    // If order is completed, refund the user
    if (order.status === 'completed' || order.status === 'processing') {
      await pool.execute(
        `UPDATE users SET balance = balance + ? WHERE id = ?`,
        [order.price, order.user_id]
      );
    }

    // Delete order
    await pool.execute(`DELETE FROM orders WHERE id = ?`, [id]);

    res.json({
      success: true,
      message: 'Order deleted successfully',
      refunded: (order.status === 'completed' || order.status === 'processing') ? order.price : 0
    });
  } catch (error) {
    console.error('[Admin Orders] Error deleting order:', error);
    res.status(500).json({
      success: false,
      error: 'Failed to delete order',
      message: error.message
    });
  }
});

module.exports = router;
