import { parseTaskContext as parseTaskContextValue } from "../../../utils/task-json.js";

export function normalizeActor(actor) {
  if (!actor || typeof actor !== "object") {
    return null;
  }

  const source = String(actor.source || "").trim();
  const userId = Number(actor.userId || 0) || 0;
  const username = String(actor.username || "").trim();
  const role = String(actor.role || "").trim();

  if (!source && !userId && !username && !role) {
    return null;
  }

  return {
    source,
    userId,
    username,
    role,
  };
}

export function parseTaskContext(task) {
  return parseTaskContextValue(task);
}

export function getTaskClaimExpiresAt(task) {
  return task?.claim_expires_at || task?.primary_claim_expires_at || null;
}

export function isClaimExpired(expiredAt) {
  if (!expiredAt) {
    return false;
  }

  const timestamp = new Date(expiredAt).getTime();
  return Number.isFinite(timestamp) && timestamp <= Date.now();
}
