import type { ITicket } from '../types';

/** Lấy ID tham chiếu từ chuỗi hoặc từ document đã populate `{ _id }`. */
export function unwrapMongoRef(value: unknown): string | undefined {
  if (value === undefined || value === null) return undefined;
  if (typeof value === 'object' && value !== null && '_id' in value) {
    const id = (value as { _id: unknown })._id;
    if (id === undefined || id === null) return undefined;
    return String(id);
  }
  if (value === '') return undefined;
  return String(value);
}

/**
 * Body PUT /tickets/:id — không gửi object populate (tránh ghi đè projectId/assetId thành object → truy vấn theo dự án không ra phiếu).
 */
export function serializeTicketForUpdate(ticket: Partial<ITicket>): Record<string, unknown> {
  const out: Record<string, unknown> = {};

  if (ticket.title !== undefined) out.title = ticket.title;
  if (ticket.description !== undefined) out.description = ticket.description;
  if (ticket.status !== undefined) out.status = ticket.status;
  if (ticket.priority !== undefined) out.priority = ticket.priority;
  if (ticket.slaDeadline !== undefined) out.slaDeadline = ticket.slaDeadline;
  if (ticket.ticketType !== undefined) out.ticketType = ticket.ticketType;

  const pid = unwrapMongoRef(ticket.projectId as unknown);
  if (pid !== undefined) out.projectId = pid;

  const aid = unwrapMongoRef(ticket.assetId as unknown);
  if (aid !== undefined) out.assetId = aid;

  const rb = unwrapMongoRef(ticket.reportedBy as unknown);
  if (rb !== undefined) out.reportedBy = rb;

  const at = unwrapMongoRef(ticket.assignedTo as unknown);
  if (ticket.assignedTo === '' || ticket.assignedTo === null) {
    out.assignedTo = '';
  } else if (at !== undefined) {
    out.assignedTo = at;
  }

  const cid = unwrapMongoRef(ticket.contractId as unknown);
  if (cid !== undefined) out.contractId = cid;

  const code = ticket.code ?? (ticket as { ticketCode?: string }).ticketCode;
  if (code !== undefined && code !== '') out.ticketCode = code;

  return out;
}

/** So khớp phiếu với dự án đang chọn (projectId có thể là chuỗi ID hoặc object populate). */
export function ticketBelongsToSelectedProject(t: ITicket, selectedProjectId: string): boolean {
  const sel = String(selectedProjectId).trim();
  if (!sel) return false;
  const unwrapped = unwrapMongoRef(t.projectId as unknown);
  if (unwrapped !== undefined && unwrapped === sel) return true;
  const raw = t.projectId as unknown;
  if (typeof raw === 'string' && raw === sel) return true;
  return false;
}
