const express = require('express');
const bcrypt = require('bcrypt');
const router = express.Router();
const db = require('../db/database');
const { getMarzbanToken, getAdminInfo } = require('../middleware/marzban');
const { requireAuth } = require('../middleware/auth');

router.get('/status', async (req, res) => {
  try {
    const [rows] = await db.query('SELECT COUNT(*) as count FROM admins');
    res.json({
      configured: rows[0].count > 0,
      loggedIn: !!req.session?.user,
      user: req.session?.user ? {
        username: req.session.user.username,
        role: req.session.user.role
      } : null
    });
  } catch (err) {
    res.status(500).json({ error: 'Database error' });
  }
});

router.post('/setup', async (req, res) => {
  try {
    const [rows] = await db.query('SELECT COUNT(*) as count FROM admins');
    if (rows[0].count > 0) {
      return res.status(400).json({ error: 'Panel already configured' });
    }

    const { panel_url, panel_username, panel_password, local_username, local_password } = req.body;

    if (!panel_url || !panel_username || !panel_password || !local_username || !local_password) {
      return res.status(400).json({ error: 'All fields are required' });
    }

    let token;
    try {
      const cleanUrl = panel_url.replace(/\/$/, '');
      token = await getMarzbanToken(cleanUrl, panel_username, panel_password);
    } catch (err) {
      return res.status(400).json({ error: 'Cannot connect to Marzban panel. Check URL and credentials.' });
    }

    const cleanUrl = panel_url.replace(/\/$/, '');
    const passwordHash = await bcrypt.hash(local_password, 12);
    const panelPasswordHash = await bcrypt.hash(panel_password, 12);

    await db.query(
      `INSERT INTO admins (username, password_hash, panel_url, panel_username, panel_password_hash, role)
       VALUES (?, ?, ?, ?, ?, 'superadmin')`,
      [local_username, passwordHash, cleanUrl, panel_username, panelPasswordHash]
    );

    await db.query(
      `INSERT INTO settings (key_name, value) VALUES ('panel_password', ?) ON DUPLICATE KEY UPDATE value = ?`,
      [panel_password, panel_password]
    );

    req.session.user = {
      id: 1,
      username: local_username,
      role: 'superadmin',
      panelUrl: cleanUrl,
      panelUsername: panel_username,
      panelPassword: panel_password,
      marzbanToken: token
    };

    res.json({ success: true, message: 'Panel configured successfully' });
  } catch (err) {
    console.error(err);
    res.status(500).json({ error: 'Setup failed: ' + err.message });
  }
});

router.post('/login', async (req, res) => {
  try {
    const { username, password } = req.body;

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

    const [adminRows] = await db.query('SELECT * FROM admins WHERE username = ?', [username]);
    
    if (adminRows.length > 0) {
      const admin = adminRows[0];
      const valid = await bcrypt.compare(password, admin.password_hash);
      if (!valid) return res.status(401).json({ error: 'Invalid credentials' });

      const [settRows] = await db.query("SELECT value FROM settings WHERE key_name = 'panel_password'");
      const panelPassword = settRows[0]?.value;

      let token;
      try {
        token = await getMarzbanToken(admin.panel_url, admin.panel_username, panelPassword);
      } catch (err) {
        return res.status(500).json({ error: 'Cannot connect to Marzban panel' });
      }

      req.session.user = {
        id: admin.id,
        username: admin.username,
        role: 'superadmin',
        panelUrl: admin.panel_url,
        panelUsername: admin.panel_username,
        panelPassword: panelPassword,
        marzbanToken: token
      };

      return res.json({ success: true, role: 'superadmin', username: admin.username });
    }

    const [resellerRows] = await db.query('SELECT * FROM resellers WHERE username = ? AND is_active = TRUE', [username]);
    
    if (resellerRows.length > 0) {
      const reseller = resellerRows[0];
      const valid = await bcrypt.compare(password, reseller.password_hash);
      if (!valid) return res.status(401).json({ error: 'Invalid credentials' });

      const [adminRows2] = await db.query('SELECT * FROM admins LIMIT 1');
      const [settRows] = await db.query("SELECT value FROM settings WHERE key_name = 'panel_password'");
      const panelPassword = settRows[0]?.value;

      let token;
      try {
        token = await getMarzbanToken(adminRows2[0].panel_url, adminRows2[0].panel_username, panelPassword);
      } catch (err) {
        return res.status(500).json({ error: 'Cannot connect to Marzban panel' });
      }

      req.session.user = {
        id: reseller.id,
        username: reseller.username,
        role: 'reseller',
        resellerId: reseller.id,
        panelUrl: adminRows2[0].panel_url,
        panelUsername: adminRows2[0].panel_username,
        panelPassword: panelPassword,
        marzbanToken: token,
        trafficLimit: reseller.traffic_limit,
        userLimit: reseller.user_limit,
        displayName: reseller.display_name
      };

      return res.json({ success: true, role: 'reseller', username: reseller.username });
    }

    return res.status(401).json({ error: 'Invalid credentials' });
  } catch (err) {
    console.error(err);
    res.status(500).json({ error: 'Login failed' });
  }
});

router.post('/logout', (req, res) => {
  req.session.destroy();
  res.json({ success: true });
});

router.post('/refresh-token', requireAuth, async (req, res) => {
  try {
    const user = req.session.user;
    const token = await getMarzbanToken(user.panelUrl, user.panelUsername, user.panelPassword);
    req.session.user.marzbanToken = token;
    res.json({ success: true });
  } catch (err) {
    res.status(500).json({ error: 'Token refresh failed' });
  }
});

module.exports = router;
