/**
 * adminPaymentGatewayRoutes.js - Payment Gateway Management API Endpoints
 * Purpose: CRUD operations for payment gateway configuration
 * Routes: 5 endpoints for payment gateway management
 */

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

// GET /api/admin/payment-gateways - List all payment gateways
router.get('/payment-gateways', async (req, res) => {
  try {
    const pool = req.app.locals.pool;
    const status = req.query.status || null;

    let whereClause = '';
    let params = [];

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

    const [gateways] = await pool.execute(
      `SELECT
        id, name, type, status, currency, min_amount, max_amount,
        percentage_charge as fee_percentage, created_at, updated_at,
        (SELECT COUNT(*) FROM deposits WHERE payment_gateway = name) as total_transactions,
        (SELECT SUM(amount) FROM deposits WHERE payment_gateway = name) as total_amount
      FROM payment_gateways
      ${whereClause}
      ORDER BY name ASC`,
      params
    );

    res.json({
      success: true,
      message: 'Payment gateways retrieved successfully',
      data: gateways
    });
  } catch (error) {
    console.error('Payment gateway list error:', error);
    res.status(500).json({
      success: false,
      error: 'Payment Gateway Error',
      message: error.message
    });
  }
});

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

    const [gateways] = await pool.execute(
      `SELECT
        id, name, type, status, currency, min_amount, max_amount,
        percentage_charge as fee_percentage, created_at, updated_at,
        (SELECT COUNT(*) FROM deposits WHERE payment_gateway = name) as total_transactions,
        (SELECT SUM(amount) FROM deposits WHERE payment_gateway = name) as total_amount
      FROM payment_gateways
      WHERE id = ?`,
      [id]
    );

    if (gateways.length === 0) {
      return res.status(404).json({
        success: false,
        error: 'Not Found',
        message: 'Payment gateway not found'
      });
    }

    // Get recent transactions
    const [transactions] = await pool.execute(
      `SELECT id, user_id, amount, status, created_at FROM deposits
       WHERE payment_gateway = ?
       ORDER BY created_at DESC
       LIMIT 10`,
      [gateways[0].name]
    );

    res.json({
      success: true,
      message: 'Payment gateway retrieved successfully',
      data: {
        ...gateways[0],
        recentTransactions: transactions
      }
    });
  } catch (error) {
    console.error('Payment gateway fetch error:', error);
    res.status(500).json({
      success: false,
      error: 'Payment Gateway Error',
      message: error.message
    });
  }
});

// POST /api/admin/payment-gateways - Create new payment gateway
router.post('/payment-gateways', async (req, res) => {
  try {
    const pool = req.app.locals.pool;
    const { name, type, currency, min_amount, max_amount, percentage_charge, status } = req.body;

    // Validate input
    if (!name) {
      return res.status(400).json({
        success: false,
        error: 'Validation Error',
        message: 'name is required'
      });
    }

    // Check if gateway already exists
    const [existing] = await pool.execute('SELECT id FROM payment_gateways WHERE name = ?', [name]);
    if (existing.length > 0) {
      return res.status(400).json({
        success: false,
        error: 'Conflict',
        message: 'Payment gateway with this name already exists'
      });
    }

    const [result] = await pool.execute(
      `INSERT INTO payment_gateways (name, type, currency, min_amount, max_amount, percentage_charge, status, created_at)
       VALUES (?, ?, ?, ?, ?, ?, ?, NOW())`,
      [name, type || 'automatic', currency || 'NGN', min_amount || 100, max_amount || 1000000, percentage_charge || 0, status || 'enabled']
    );

    res.status(201).json({
      success: true,
      message: 'Payment gateway created successfully',
      data: {
        id: result.insertId,
        name,
        type: type || 'automatic',
        status: status || 'enabled'
      }
    });
  } catch (error) {
    console.error('Payment gateway create error:', error);
    res.status(500).json({
      success: false,
      error: 'Create Error',
      message: error.message
    });
  }
});

// PUT /api/admin/payment-gateways/:id - Update payment gateway
router.put('/payment-gateways/:id', async (req, res) => {
  try {
    const pool = req.app.locals.pool;
    const { id } = req.params;
    const { type, currency, min_amount, max_amount, percentage_charge, status } = req.body;

    // Verify gateway exists
    const [existing] = await pool.execute('SELECT id FROM payment_gateways WHERE id = ?', [id]);
    if (existing.length === 0) {
      return res.status(404).json({
        success: false,
        error: 'Not Found',
        message: 'Payment gateway not found'
      });
    }

    // Build update query dynamically
    const updates = [];
    const values = [];
    if (type !== undefined) { updates.push('type = ?'); values.push(type); }
    if (currency !== undefined) { updates.push('currency = ?'); values.push(currency); }
    if (min_amount !== undefined) { updates.push('min_amount = ?'); values.push(min_amount); }
    if (max_amount !== undefined) { updates.push('max_amount = ?'); values.push(max_amount); }
    if (percentage_charge !== undefined) { updates.push('percentage_charge = ?'); values.push(percentage_charge); }
    if (status !== undefined) { updates.push('status = ?'); values.push(status); }

    if (updates.length > 0) {
      updates.push('updated_at = NOW()');
      values.push(id);
      await pool.execute(
        `UPDATE payment_gateways SET ${updates.join(', ')} WHERE id = ?`,
        values
      );
    }

    res.json({
      success: true,
      message: 'Payment gateway updated successfully',
      data: { id }
    });
  } catch (error) {
    console.error('Payment gateway update error:', error);
    res.status(500).json({
      success: false,
      error: 'Update Error',
      message: error.message
    });
  }
});

// PUT /api/admin/payment-gateways/:id/status - Toggle gateway status
router.put('/payment-gateways/:id/status', async (req, res) => {
  try {
    const pool = req.app.locals.pool;
    const { id } = req.params;
    const { status } = req.body;

    if (!status || !['enabled', 'disabled'].includes(status)) {
      return res.status(400).json({
        success: false,
        error: 'Validation Error',
        message: 'status must be "enabled" or "disabled"'
      });
    }

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

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

    res.json({
      success: true,
      message: `Payment gateway ${status} successfully`,
      data: { id, status }
    });
  } catch (error) {
    console.error('Payment gateway status update error:', error);
    res.status(500).json({
      success: false,
      error: 'Update Error',
      message: error.message
    });
  }
});

// DELETE /api/admin/payment-gateways/:id - Delete payment gateway
router.delete('/payment-gateways/:id', async (req, res) => {
  try {
    const pool = req.app.locals.pool;
    const { id } = req.params;

    // Check if gateway has transactions
    const [gateway] = await pool.execute('SELECT name FROM payment_gateways WHERE id = ?', [id]);
    if (gateway.length === 0) {
      return res.status(404).json({
        success: false,
        error: 'Not Found',
        message: 'Payment gateway not found'
      });
    }

    const [transactions] = await pool.execute(
      'SELECT id FROM deposits WHERE payment_gateway = ?',
      [gateway[0].name]
    );

    if (transactions.length > 0) {
      return res.status(400).json({
        success: false,
        error: 'Conflict',
        message: `Cannot delete gateway with ${transactions.length} transactions. Archive it instead.`
      });
    }

    // Delete gateway
    await pool.execute('DELETE FROM payment_gateways WHERE id = ?', [id]);

    res.json({
      success: true,
      message: 'Payment gateway deleted successfully'
    });
  } catch (error) {
    console.error('Payment gateway delete error:', error);
    res.status(500).json({
      success: false,
      error: 'Delete Error',
      message: error.message
    });
  }
});

module.exports = router;
