const { query } = require('../config/db');

// ─────────────────────────────────────────────────────────────────
// GET /api/leave/team-members
// Returns employees under the requesting manager.
// Used by Step 2 coverage picker.
// If role is hr/admin, returns all employees in the org.
// ─────────────────────────────────────────────────────────────────
async function getTeamMembers(req, res) {
  const { id: user_id, org_id, role } = req.user;

  try {
    let rows;

    const isHrOrAdmin = ['admin', 'hr', 'hr_admin'].includes(role);

    if (isHrOrAdmin) {
      // HR/admin sees everyone in the org
      const result = await query(
        `SELECT
  u.id,
  u.name,
  LEFT(u.name, 2)                         AS initials,
  COALESCE(d.dept_name, 'General')        AS role,
  u.department_id,
  u.designation_id
FROM users u
INNER JOIN employees e ON e.email = u.email AND e.org_id = u.org_id
LEFT JOIN departments d ON d.id = u.department_id
WHERE u.org_id = $1
  AND u.is_deleted = false
  AND e.status = 'Active'
  AND e.is_deleted = false
  AND u.id != $2
ORDER BY u.name`,
        [org_id, user_id]
      );
      rows = result.rows;
    } else {
      // Manager sees their direct reports
      const result = await query(
        `SELECT
  u.id,
  u.name,
  LEFT(u.name, 2)                         AS initials,
  COALESCE(d.dept_name, 'General')        AS role,
  u.department_id
FROM team_members tm
JOIN users u ON u.id = tm.employee_id
INNER JOIN employees e ON e.email = u.email AND e.org_id = u.org_id
LEFT JOIN departments d ON d.id = u.department_id
WHERE tm.manager_id  = $1
  AND tm.org_id      = $2
  AND tm.is_deleted  = false
  AND u.is_deleted   = false
  AND e.status = 'Active'
  AND e.is_deleted = false
ORDER BY u.name`,
        [user_id, org_id]
      );
      rows = result.rows;
    }

    res.json({ success: true, data: rows });
  } catch (err) {
    console.error('getTeamMembers:', err);
    res.status(500).json({ success: false, message: 'Internal server error' });
  }
}

module.exports = { getTeamMembers };