import express from 'express';
import { body, validationResult } from 'express-validator';
import { dbRun, dbGet, dbAll } from '../config/database.js';
import { authenticateToken, isAdmin } from '../middleware/auth.js';

const router = express.Router();

// Validation for exchange request
const exchangeRequestValidation = [
  body('name').trim().notEmpty().withMessage('Name is required'),
  body('email').isEmail().withMessage('Valid email is required'),
  body('phone').trim().notEmpty().withMessage('Phone number is required'),
  body('amount').isFloat({ min: 0.01 }).withMessage('Valid amount is required'),
  body('currencyFrom').isIn(['ZAR', 'NGN']).withMessage('Valid currency is required'),
  body('currencyTo').isIn(['ZAR', 'NGN']).withMessage('Valid currency is required')
];

// Submit exchange request (public)
router.post('/request', exchangeRequestValidation, async (req, res) => {
  try {
    const errors = validationResult(req);
    if (!errors.isEmpty()) {
      return res.status(400).json({ 
        success: false, 
        errors: errors.array() 
      });
    }

    const { name, email, phone, amount, currencyFrom, currencyTo } = req.body;

    const result = await dbRun(
      `INSERT INTO exchange_requests 
       (name, email, phone, amount, currency_from, currency_to, status) 
       VALUES (?, ?, ?, ?, ?, ?, 'pending')`,
      [name, email, phone, amount, currencyFrom, currencyTo]
    );

    res.status(201).json({
      success: true,
      message: 'Exchange request submitted successfully',
      requestId: result.lastID
    });
  } catch (error) {
    if (process.env.NODE_ENV !== 'production') {
      console.error('Exchange request error:', error);
    }
    res.status(500).json({ 
      success: false, 
      message: 'Server error while submitting request' 
    });
  }
});

// Get all exchange requests (admin only)
router.get('/requests', authenticateToken, isAdmin, async (req, res) => {
  try {
    const { status, page = 1, limit = 10 } = req.query;
    const offset = (page - 1) * limit;

    let query = 'SELECT * FROM exchange_requests';
    let params = [];

    if (status) {
      query += ' WHERE status = ?';
      params.push(status);
    }

    query += ' ORDER BY created_at DESC LIMIT ? OFFSET ?';
    params.push(parseInt(limit), offset);

    const requests = await dbAll(query, params);
    
    // Ensure requests is always an array
    const safeRequests = Array.isArray(requests) ? requests : [];

    // Get total count
    let countQuery = 'SELECT COUNT(*) as total FROM exchange_requests';
    if (status) {
      countQuery += ' WHERE status = ?';
    }
    const countResult = await dbGet(countQuery, status ? [status] : []);
    const total = (countResult && countResult.total) ? countResult.total : safeRequests.length;

    res.json({
      success: true,
      requests: safeRequests,
      pagination: {
        page: parseInt(page),
        limit: parseInt(limit),
        total,
        pages: Math.ceil(total / limit)
      }
    });
  } catch (error) {
    if (process.env.NODE_ENV !== 'production') {
      console.error('Get requests error:', error);
    }
    res.status(500).json({ 
      success: false, 
      message: 'Server error while fetching requests',
      requests: [], // Provide empty array as fallback
      pagination: {
        page: parseInt(req.query.page || 1),
        limit: parseInt(req.query.limit || 10),
        total: 0,
        pages: 0
      }
    });
  }
});

// Update exchange request status (admin only)
router.patch('/requests/:id', authenticateToken, isAdmin, async (req, res) => {
  try {
    const { id } = req.params;
    const { status } = req.body;

    if (!['pending', 'processing', 'completed', 'cancelled'].includes(status)) {
      return res.status(400).json({ 
        success: false, 
        message: 'Invalid status' 
      });
    }

    await dbRun(
      'UPDATE exchange_requests SET status = ?, updated_at = CURRENT_TIMESTAMP WHERE id = ?',
      [status, id]
    );

    res.json({
      success: true,
      message: 'Request status updated successfully'
    });
  } catch (error) {
    if (process.env.NODE_ENV !== 'production') {
      console.error('Update request error:', error);
    }
    res.status(500).json({ 
      success: false, 
      message: 'Server error while updating request' 
    });
  }
});

// Get current exchange rates (public)
router.get('/rates', async (req, res) => {
  try {
    const rates = await dbAll('SELECT * FROM exchange_rates');

    // Ensure rates is always an array
    const safeRates = Array.isArray(rates) ? rates : [];

    res.json({
      success: true,
      rates: safeRates.map(rate => ({
        currencyPair: rate.currency_pair || rate.currencyPair,
        buyRate: rate.buy_rate || rate.buyRate || 0,
        sellRate: rate.sell_rate || rate.sellRate || 0,
        updatedAt: rate.updated_at || rate.updatedAt || new Date().toISOString()
      }))
    });
  } catch (error) {
    if (process.env.NODE_ENV !== 'production') {
      console.error('Get rates error:', error);
    }
    res.status(500).json({ 
      success: false, 
      message: 'Server error while fetching rates',
      rates: [] // Provide empty array as fallback
    });
  }
});

// Update exchange rates (admin only)
router.put('/rates/:currencyPair', authenticateToken, isAdmin, async (req, res) => {
  try {
    const { currencyPair } = req.params;
    const { buyRate, sellRate } = req.body;

    if (!buyRate || !sellRate) {
      return res.status(400).json({ 
        success: false, 
        message: 'Both buy and sell rates are required' 
      });
    }

    await dbRun(
      `UPDATE exchange_rates 
       SET buy_rate = ?, sell_rate = ?, updated_at = CURRENT_TIMESTAMP 
       WHERE currency_pair = ?`,
      [buyRate, sellRate, currencyPair]
    );

    res.json({
      success: true,
      message: 'Exchange rates updated successfully'
    });
  } catch (error) {
    if (process.env.NODE_ENV !== 'production') {
      console.error('Update rates error:', error);
    }
    res.status(500).json({ 
      success: false, 
      message: 'Server error while updating rates' 
    });
  }
});

export default router;
