import { formatAssignmentDateTime } from "./assignmentDisplay.js";

const STORAGE_PREFIX = "swi-assignment-seen";

function storageKey(userId) {
  return `${STORAGE_PREFIX}-${userId}`;
}

/** Unique key per assignment event (re-assignments with new assigned_at re-notify). */
export function assignmentNotifyKey(row) {
  const at = row?.assigned_at ? new Date(row.assigned_at).getTime() : 0;
  return `${row.document_id}-${row.document_number}-${at}`;
}

export function loadSeenAssignmentKeys(userId) {
  if (userId == null || userId === "") return new Set();
  try {
    const raw = localStorage.getItem(storageKey(userId));
    const parsed = JSON.parse(raw || "[]");
    return new Set(Array.isArray(parsed) ? parsed : []);
  } catch {
    return new Set();
  }
}

export function saveSeenAssignmentKeys(userId, keys) {
  if (userId == null || userId === "") return;
  try {
    localStorage.setItem(storageKey(userId), JSON.stringify([...keys]));
  } catch {
    /* ignore quota errors */
  }
}

export function getUnreadAssignments(assignments = [], seenKeys = new Set()) {
  return assignments.filter(
    (row) => row.assigned_at && !seenKeys.has(assignmentNotifyKey(row))
  );
}

export function sortByAssignedAt(assignments = []) {
  return [...assignments].sort((a, b) => {
    const ta = a.assigned_at ? new Date(a.assigned_at).getTime() : 0;
    const tb = b.assigned_at ? new Date(b.assigned_at).getTime() : 0;
    return tb - ta;
  });
}

export function assignmentNotificationMessage(row) {
  const name = (row.document_name || "").trim() || `Document ${row.document_id}`;
  const when = formatAssignmentDateTime(row.assigned_at);
  return {
    title: name,
    body: `Assigned to you${when !== "—" ? ` · ${when}` : ""}`,
  };
}
