import { pool } from "../config/db.js";

/**
 * List `orac_participants` with `participant_name` resolved from `users.employee_name`
 * (and optional `participants_name` on the row). Replaces generic `SELECT *` list.
 */
export async function listOracParticipantsWithNames(req, res, next) {
  try {
    const filters = req.query || {};
    const whereParts = [];
    const values = [];

    Object.entries(filters).forEach(([key, value]) => {
      if (value === undefined || value === null || value === "") {
        return;
      }
      if (key.endsWith("_like")) {
        const column = key.slice(0, -5);
        whereParts.push(`op.\`${column}\` LIKE ?`);
        values.push(`%${value}%`);
      } else {
        whereParts.push(`op.\`${key}\` = ?`);
        values.push(value);
      }
    });

    let sql = `
      SELECT
        op.assessment_id,
        op.participant_user_id,
        op.participants_name,
        (
          SELECT u.employee_name
          FROM users u
          WHERE u.user_id = op.participant_user_id
          LIMIT 1
        ) AS participant_name
      FROM orac_participants op
    `;
    if (whereParts.length) {
      sql += ` WHERE ${whereParts.join(" AND ")}`;
    }

    const [rows] = await pool.query(sql, values);
    res.json(rows);
  } catch (err) {
    next(err);
  }
}
