/**
 * Shared guards for commands that only run in mapped ServChan WO spaces.
 */

import { parseServChanRoomTitle } from './servchanRoomTitle.js';

const WO_SPACE_MSG = 'This command can only be used in a ServChan work order space.';

function lookupWorkOrderIdByRoom(db, roomId) {
  return new Promise((resolve, reject) => {
    db.get(
      'SELECT workOrderId FROM mappings WHERE roomId = ?',
      [roomId],
      (err, row) => (err ? reject(err) : resolve(row?.workOrderId ?? null))
    );
  });
}

/**
 * @returns {Promise<{ ok: true, workOrderId, roomId, parsed, room } | { ok: false, error: string }>}
 */
export async function resolveWoRoomContext({ db, botClient, roomId, isGroup }) {
  if (!isGroup || !roomId) {
    return { ok: false, error: WO_SPACE_MSG };
  }

  const workOrderId = await lookupWorkOrderIdByRoom(db, roomId);
  if (!workOrderId) {
    return { ok: false, error: WO_SPACE_MSG };
  }

  let room;
  try {
    room = await botClient.getRoom(roomId);
  } catch {
    return { ok: false, error: 'Could not load this Webex space. Please try again.' };
  }

  const parsed = parseServChanRoomTitle(room?.title);
  if (!parsed) {
    return { ok: false, error: WO_SPACE_MSG };
  }

  return { ok: true, workOrderId, roomId, parsed, room };
}

export async function resolveDisplayName(botClient, personId) {
  if (!personId) return 'Unknown User';
  try {
    const person = await botClient.getPersonDetails(personId);
    return person?.displayName || person?.emails?.[0] || 'Unknown User';
  } catch {
    return 'Unknown User';
  }
}

export default { resolveWoRoomContext, resolveDisplayName };
