import db from '../config/database.js';

export const getWalletBalance = async (req, res) => {
  try {
    const { role, id } = req.user;

    // ── Member ───────────────────────────────────────────────
    if (role === 'member') {
      const [[data]] = await db.query(
        `SELECT
           COALESCE(wallet_balance, 0) AS wallet_balance,
           COALESCE(total_income,   0) AS total_income,
           COALESCE(star_club_income,   0) AS star_club_income,
           COALESCE(ppp_income,     0) AS ppp_income,
           COALESCE(tri_income,     0) AS tri_income,
           COALESCE(roylty_income,     0) AS roylty_income,
           COALESCE(level_income,   0) AS level_income
         FROM members WHERE id = ?`,
        [id]
      );

      if (!data)
        return res.status(404).json({ success: false, message: 'Member not found' });

      return res.json({
        success: true,
        role: 'member',
        data: {
          wallet_balance: parseFloat(data.wallet_balance),
          total_income:   parseFloat(data.total_income),
          breakdown: {
            star_club_income:  parseFloat(data.star_club_income),
            ppp_income:    parseFloat(data.ppp_income),
            tri_income:    parseFloat(data.tri_income),
            roylty_income:    parseFloat(data.roylty_income),
            level_income:  parseFloat(data.level_income),
          },
        },
      });
    }

    // ── Customer ─────────────────────────────────────────────
    if (role === 'customer') {
      const [[data]] = await db.query(
        `SELECT
           COALESCE(wallet_balance,  0) AS wallet_balance,
           COALESCE(total_income,    0) AS total_income,
           COALESCE(cashback_income, 0) AS cashback_income
         FROM customers WHERE id = ?`,
        [id]
      );

      if (!data)
        return res.status(404).json({ success: false, message: 'Customer not found' });

      return res.json({
        success: true,
        role: 'customer',
        data: {
          wallet_balance:  parseFloat(data.wallet_balance),
          total_income:    parseFloat(data.total_income),
          cashback_income: parseFloat(data.cashback_income),
      
        },
      });
    }

    return res.status(400).json({ success: false, message: 'Invalid role' });

  } catch (error) {
    console.error('❌ getWalletBalance error:', error.message);
    res.status(500).json({ success: false, message: 'Server error', error: error.message });
  }
};

export const getTransactionHistory = async (req, res) => {
  try {
    const { id } = req.user;

    const [data] = await db.query(
      'SELECT * FROM transactions WHERE user_id = ? ORDER BY created_at DESC',
      [id]
    );

    res.json({ success: true, data });
  } catch (error) {
    console.error('getTransactionHistory error:', error.message);
    res.status(500).json({ success: false, message: 'Server error', error: error.message });
  }
};

export const requestWithdrawal = async (req, res) => {
  try {
    const { amount, bank_details } = req.body;
    const { role, id } = req.user;
    const user_member_id = role === 'customer' ? req.user.customer_id : req.user.member_id;

    if (amount < 500) {
      return res.status(400).json({ success: false, message: 'Minimum withdrawal amount is ₹500' });
    }

    const table = role === 'customer' ? 'customers' : 'members';
    const [userResult] = await db.query(
      `SELECT wallet_balance FROM ${table} WHERE id = ?`,
      [id]
    );

    if (!userResult || userResult.length === 0) {
      return res.status(404).json({ success: false, message: 'User not found' });
    }

    if (userResult[0].wallet_balance < amount) {
      return res.status(400).json({ success: false, message: 'Insufficient wallet balance' });
    }

    const [result] = await db.query(
      'INSERT INTO withdrawals (user_type, user_id, user_member_id, amount, bank_details, status) VALUES (?, ?, ?, ?, ?, ?)',
      [role, id, user_member_id, amount, JSON.stringify(bank_details), 'Pending']
    );

    if (!result || !result.insertId) {
      return res.status(500).json({ success: false, message: 'Withdrawal request failed' });
    }

    const [data] = await db.query('SELECT * FROM withdrawals WHERE id = ?', [result.insertId]);

    res.status(201).json({
      success: true,
      message: 'Withdrawal request submitted successfully',
      data: data[0]
    });
  } catch (error) {
    console.error('requestWithdrawal error:', error.message);
    res.status(500).json({ success: false, message: 'Server error', error: error.message });
  }
};

export const getWithdrawalHistory = async (req, res) => {
  try {
    const { id } = req.user;
    const [data] = await db.query(
      'SELECT * FROM withdrawals WHERE user_id = ? ORDER BY created_at DESC',
      [id]
    );
    res.json({ success: true, data });
  } catch (error) {
    console.error('getWithdrawalHistory error:', error.message);
    res.status(500).json({ success: false, message: 'Server error', error: error.message });
  }
};

export const approveWithdrawal = async (req, res) => {
  try {
    const { id } = req.params;
    const { admin_remarks } = req.body;

    const [withdrawalResult] = await db.query('SELECT * FROM withdrawals WHERE id = ?', [id]);
    if (!withdrawalResult || withdrawalResult.length === 0)
      return res.status(404).json({ success: false, message: 'Withdrawal request not found' });

    const withdrawal = withdrawalResult[0];
    const table = withdrawal.user_type === 'customer' ? 'customers' : 'members';

    const [userResult] = await db.query(`SELECT wallet_balance FROM ${table} WHERE id = ?`, [withdrawal.user_id]);
    if (!userResult || userResult.length === 0 || userResult[0].wallet_balance < withdrawal.amount)
      return res.status(400).json({ success: false, message: 'Insufficient wallet balance' });

    await db.query(`UPDATE ${table} SET wallet_balance = wallet_balance - ? WHERE id = ?`, [withdrawal.amount, withdrawal.user_id]);
    await db.query('UPDATE withdrawals SET status = ?, admin_remarks = ?, updated_at = NOW() WHERE id = ?', ['Approved', admin_remarks, id]);
    await db.query(
      'INSERT INTO transactions (user_type, user_id, user_member_id, transaction_type, amount, description) VALUES (?, ?, ?, ?, ?, ?)',
      [withdrawal.user_type, withdrawal.user_id, withdrawal.user_member_id, 'WITHDRAWAL', -withdrawal.amount, 'Withdrawal approved']
    );

    res.json({ success: true, message: 'Withdrawal approved successfully' });
  } catch (error) {
    console.error('approveWithdrawal error:', error.message);
    res.status(500).json({ success: false, message: 'Server error', error: error.message });
  }
};

export const rejectWithdrawal = async (req, res) => {
  try {
    const { id } = req.params;
    const { admin_remarks } = req.body;
    await db.query('UPDATE withdrawals SET status = ?, admin_remarks = ?, updated_at = NOW() WHERE id = ?', ['Rejected', admin_remarks, id]);
    res.json({ success: true, message: 'Withdrawal request rejected' });
  } catch (error) {
    console.error('rejectWithdrawal error:', error.message);
    res.status(500).json({ success: false, message: 'Server error', error: error.message });
  }
};