const express = require('express');
const bcrypt = require('bcrypt');
const router = express.Router();
const db = require('../db/database');
const { requireAdmin } = require('../middleware/auth');

router.get('/', requireAdmin, async (req, res) => {
  try {
    const [rows] = await db.query(
      'SELECT id, username, display_name, traffic_limit, user_limit, used_traffic, user_count, is_active, notes, created_at FROM resellers ORDER BY created_at DESC'
    );
    res.json(rows);
  } catch (err) {
    res.status(500).json({ error: 'Failed to fetch resellers' });
  }
});

router.post('/', requireAdmin, async (req, res) => {
  try {
    const { username, password, display_name, traffic_limit, user_limit, notes } = req.body;

    if (!username || !password) {
      return res.status(400).json({ error: 'Username and password required' });
    }

    const [existing] = await db.query('SELECT id FROM resellers WHERE username = ?', [username]);
    if (existing.length > 0) {
      return res.status(400).json({ error: 'Username already exists' });
    }

    const passwordHash = await bcrypt.hash(password, 12);
    const trafficBytes = traffic_limit ? BigInt(Math.floor(parseFloat(traffic_limit) * 1024 * 1024 * 1024)) : 0;

    const [result] = await db.query(
      `INSERT INTO resellers (username, password_hash, display_name, traffic_limit, user_limit, notes)
       VALUES (?, ?, ?, ?, ?, ?)`,
      [username, passwordHash, display_name || username, trafficBytes.toString(), user_limit || 0, notes || '']
    );

    res.json({ success: true, id: result.insertId });
  } catch (err) {
    console.error(err);
    res.status(500).json({ error: 'Failed to create reseller: ' + err.message });
  }
});

router.put('/:id', requireAdmin, async (req, res) => {
  try {
    const { display_name, traffic_limit, user_limit, is_active, notes, password } = req.body;
    const { id } = req.params;

    let query = 'UPDATE resellers SET display_name=?, traffic_limit=?, user_limit=?, is_active=?, notes=?';
    const trafficBytes = traffic_limit ? BigInt(Math.floor(parseFloat(traffic_limit) * 1024 * 1024 * 1024)) : 0;
    const params = [display_name, trafficBytes.toString(), user_limit || 0, is_active !== false, notes || ''];

    if (password) {
      const hash = await bcrypt.hash(password, 12);
      query += ', password_hash=?';
      params.push(hash);
    }

    query += ' WHERE id=?';
    params.push(id);

    await db.query(query, params);
    res.json({ success: true });
  } catch (err) {
    res.status(500).json({ error: 'Failed to update reseller' });
  }
});

router.delete('/:id', requireAdmin, async (req, res) => {
  try {
    await db.query('DELETE FROM resellers WHERE id = ?', [req.params.id]);
    res.json({ success: true });
  } catch (err) {
    res.status(500).json({ error: 'Failed to delete reseller' });
  }
});

module.exports = router;
