const express = require('express');
const bcrypt = require('bcrypt');
const pool = require('../db');
const verifyUserToken = require('../middleware/authClient');
const requireOrgPermission = require('../middleware/requireOrgPermission');
const { sendUserInviteEmail } = require('../utils/emailSender');


const router = express.Router();

/* -----------------------------------
   GET ORGANIZATION USERS (DASHBOARD)
------------------------------------ */

router.get('/', verifyUserToken, async (req, res) => {

  try {

    const orgId = req.user.organizationId;

    const [rows] = await pool.query(
      `
      SELECT
        id,
        email,
        firstName,
        lastName,
        role,
        avatar,
        is_online,
        last_seen,
        isActive
      FROM users
      WHERE organizationId = ?
      ORDER BY is_online DESC, firstName ASC
      `,
      [orgId]
    );

    console.log('ORG USERS RESULT:', rows);

    res.json(rows);

  } catch (err) {

    console.error('GET /users error:', err);
    res.status(500).json({ success: false });

  }
});


/* -----------------------------------
   GET ORG USERS (LIMITED LIST - INVITES ETC)
------------------------------------ */

router.get(
  '/org',
  verifyUserToken,
  requireOrgPermission(),
  async (req, res) => {

    try {

      const { organizationId } = req.user;

      const [users] = await pool.query(
        `
        SELECT 
          id,
          firstName,
          lastName,
          email,
          role
        FROM users
        WHERE organizationId = ?
        ORDER BY firstName, lastName
        `,
        [organizationId]
      );

      res.json({
        success: true,
        users
      });

    } catch (err) {

      console.error('ORG LIST ERROR:', err);
      res.status(500).json({ success: false });

    }
  }
);


/* -----------------------------------
   SAVE FCM TOKEN
------------------------------------ */

router.post('/save-fcm-token', verifyUserToken, async (req, res) => {

  const { userId } = req.user;
  const { token } = req.body;

  if (!token) {
    return res.status(400).json({ error: 'Missing token' });
  }

  try {

    await pool.query(
      `
      INSERT IGNORE INTO user_fcm_tokens (userId, token)
      VALUES (?, ?)
      `,
      [userId, token]
    );

    res.json({ success: true });

  } catch (err) {

    console.error('FCM save error:', err);
    res.status(500).json({ error: 'Failed saving token' });

  }
});


/* -----------------------------------
   ENABLE / DISABLE USER (ADMIN)
------------------------------------ */

router.patch('/:id/status', verifyUserToken, async (req, res) => {

  try {

    if (req.user.role !== 'admin' && req.user.role !== 'owner') {
      return res.status(403).json({ success: false });
    }

    const userId = req.params.id;
    const { isActive } = req.body;

    if (typeof isActive === 'undefined') {
      return res.status(400).json({ success: false });
    }

    // Prevent self lockout
    if (req.user.id == userId) {
      return res.status(400).json({
        success: false,
        message: 'You cannot disable your own account'
      });
    }

    await pool.query(
      `UPDATE users SET isActive = ? WHERE id = ?`,
      [isActive, userId]
    );

    res.json({
      success: true
    });

  } catch (err) {

    console.error('User status update error:', err);
    res.status(500).json({ success: false });

  }
});


/* -----------------------------------
   RESET USER PASSWORD (ADMIN)
------------------------------------ */

router.post('/:id/reset-password', verifyUserToken, async (req, res) => {

  try {

    if (req.user.role !== 'admin' && req.user.role !== 'owner') {
      return res.status(403).json({ success: false });
    }

    const userId = req.params.id;

    // Generate temp password
    const tempPassword = Math.random().toString(36).slice(-10);

    // Hash password
    const hash = await bcrypt.hash(tempPassword, 10);

    await pool.query(
      `
      UPDATE users 
      SET password_hash = ?, forcePasswordChange = 1 
      WHERE id = ?
      `,
      [hash, userId]
    );

    const [rows] = await pool.query(
      `SELECT email FROM users WHERE id = ?`,
      [userId]
    );

    const email = rows[0]?.email;
    
    await sendTempPassword({ to: email, tempPassword });


    console.log(`TEMP PASSWORD for ${email}:`, tempPassword);

    res.json({
      success: true
    });

  } catch (err) {

    console.error('Password reset error:', err);
    res.status(500).json({ success: false });

  }
});


/* -----------------------------------
   LOGOUT
------------------------------------ */

router.post('/logout', verifyUserToken, async (req, res) => {

  try {

    res.json({ success: true });

  } catch (err) {

    console.error('Logout error:', err);
    res.status(500).json({ success: false });

  }
});


/* -----------------------------------
   UPDATE USER ROLE (OWNER ONLY)
------------------------------------ */

router.patch('/:id/role', verifyUserToken, async (req, res) => {

  try {

    const requester = req.user;

    // Only OWNER can change roles
    if (requester.role !== 'owner') {
      return res.status(403).json({
        success: false,
        message: 'Only owner can change roles'
      });
    }

    const targetUserId = req.params.id;
    const { role } = req.body;

    const allowedRoles = ['admin', 'member'];

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

    // Prevent self downgrade
    if (requester.id == targetUserId) {
      return res.status(400).json({
        success: false,
        message: 'You cannot change your own role'
      });
    }

    // Prevent modifying users outside org
    const [rows] = await pool.query(
      `
      SELECT id, role FROM users
      WHERE id = ? AND organizationId = ?
      `,
      [targetUserId, requester.organizationId]
    );

    if (!rows.length) {
      return res.status(404).json({ success: false });
    }

    // Prevent changing another owner
    if (rows[0].role === 'owner') {
      return res.status(403).json({
        success: false,
        message: 'Owner role cannot be changed'
      });
    }

    await pool.query(
      `
      UPDATE users SET role = ?
      WHERE id = ?
      `,
      [role, targetUserId]
    );

    res.json({ success: true });

  } catch (err) {

    console.error('ROLE UPDATE ERROR:', err);
    res.status(500).json({ success: false });

  }
});


module.exports = router;
