import type { ITicket } from '../types';

/** `projectId` từ API có thể là string hoặc object populate `{ _id, name, code }`. */
export function getTicketProjectIdString(t: ITicket): string {
  const raw = t.projectId as unknown;
  if (raw == null || raw === '') return '';
  if (typeof raw === 'string') return raw;
  if (typeof raw === 'object' && '_id' in (raw as object)) {
    const id = (raw as { _id: unknown })._id;
    if (id != null && typeof (id as { toString?: () => string }).toString === 'function') {
      return String((id as { toString: () => string }).toString());
    }
    return id != null ? String(id) : '';
  }
  return String(raw);
}

export function getTicketProjectName(t: ITicket, nameById: Map<string, string>): string {
  const raw = t.projectId as unknown;
  if (raw && typeof raw === 'object' && raw !== null && 'name' in raw) {
    const name = (raw as { name?: string }).name;
    if (typeof name === 'string' && name.trim()) return name.trim();
  }
  const idStr = getTicketProjectIdString(t);
  return nameById.get(idStr) || '—';
}
