const express = require('express');
const router = express.Router();
const { requireAuth } = require('../middleware/auth');
const { getUsers, getUser, createUser, updateUser, deleteUser, resetUserTraffic, getMarzbanToken, getInbounds } = require('../middleware/marzban');

async function getToken(req) {
  try {
    return await getMarzbanToken(req.session.user.panelUrl, req.session.user.panelUsername, req.session.user.panelPassword);
  } catch {
    return req.session.user.marzbanToken;
  }
}

router.get('/', requireAuth, async (req, res) => {
  try {
    const user = req.session.user;
    const token = await getToken(req);
    
    const params = {};
    if (req.query.search) params.search = req.query.search;
    if (req.query.status) params.status = req.query.status;
    if (req.query.offset) params.offset = req.query.offset;
    if (req.query.limit) params.limit = req.query.limit;
    else params.limit = 50;

    const data = await getUsers(user.panelUrl, token, params);
    res.json(data);
  } catch (err) {
    console.error(err);
    res.status(500).json({ error: 'Failed to fetch users: ' + err.message });
  }
});

router.get('/:username', requireAuth, async (req, res) => {
  try {
    const user = req.session.user;
    const token = await getToken(req);
    const data = await getUser(user.panelUrl, token, req.params.username);
    res.json(data);
  } catch (err) {
    res.status(500).json({ error: 'Failed to fetch user' });
  }
});

router.post('/', requireAuth, async (req, res) => {
  try {
    const user = req.session.user;
    const token = await getToken(req);
    const userData = req.body;
    const data = await createUser(user.panelUrl, token, userData);
    res.json(data);
  } catch (err) {
    console.error(err);
    res.status(500).json({ error: 'Failed to create user: ' + (err.response?.data?.detail || err.message) });
  }
});

router.put('/:username', requireAuth, async (req, res) => {
  try {
    const user = req.session.user;
    const token = await getToken(req);
    const data = await updateUser(user.panelUrl, token, req.params.username, req.body);
    res.json(data);
  } catch (err) {
    res.status(500).json({ error: 'Failed to update user: ' + (err.response?.data?.detail || err.message) });
  }
});

router.delete('/:username', requireAuth, async (req, res) => {
  try {
    const user = req.session.user;
    const token = await getToken(req);
    await deleteUser(user.panelUrl, token, req.params.username);
    res.json({ success: true });
  } catch (err) {
    res.status(500).json({ error: 'Failed to delete user' });
  }
});

router.post('/:username/reset', requireAuth, async (req, res) => {
  try {
    const user = req.session.user;
    const token = await getToken(req);
    const data = await resetUserTraffic(user.panelUrl, token, req.params.username);
    res.json(data);
  } catch (err) {
    res.status(500).json({ error: 'Failed to reset traffic' });
  }
});

router.get('/meta/inbounds', requireAuth, async (req, res) => {
  try {
    const user = req.session.user;
    const token = await getToken(req);
    const data = await getInbounds(user.panelUrl, token);
    res.json(data);
  } catch (err) {
    res.status(500).json({ error: 'Failed to fetch inbounds' });
  }
});

module.exports = router;
