import db from '../../db.js';

function mapAssignable(r) {
  return {
    id: r.id,
    username: r.username,
    firstName: r.firstname ?? null,
    lastName: r.lastname ?? null,
  };
}

/** Aktive CRM-Benutzer für Ticket-Zuweisung (Dropdown). */
export function registerAssignableUserRoutes(api) {
  api.get('/assignable-users', (_req, res) => {
    const rows = db
      .prepare(
        `SELECT id, username, firstname, lastname FROM users
         WHERE active = 1
         ORDER BY
           COALESCE(lastname, '') COLLATE NOCASE ASC,
           COALESCE(firstname, '') COLLATE NOCASE ASC,
           username COLLATE NOCASE ASC`,
      )
      .all();
    res.json(rows.map(mapAssignable));
  });
}
