// Local-only collaboration activity log shared between the detail-page
// CollaborationPanel and the row-level action modals. No backend.

export type EditEntry = {
  action: "edit";
  userId: string;
  userName: string;
  timestamp: string;
  notes?: string;
  taggedCollaboratorIds: string[];
};

export type CommentEntry = {
  action: "comment";
  userId: string;
  userName: string;
  timestamp: string;
  comment: string;
  taggedCollaboratorIds: string[];
};

export type ActivityEntry = EditEntry | CommentEntry;

const STORAGE_PREFIX = "collab-activity:";

export const loadActivity = (recordId: string): ActivityEntry[] => {
  try {
    const raw = localStorage.getItem(STORAGE_PREFIX + recordId);
    if (!raw) return [];
    const parsed = JSON.parse(raw);
    return Array.isArray(parsed) ? parsed : [];
  } catch {
    return [];
  }
};

export const saveActivity = (
  recordId: string,
  entries: ActivityEntry[],
): void => {
  try {
    localStorage.setItem(STORAGE_PREFIX + recordId, JSON.stringify(entries));
  } catch {
    // localStorage may be unavailable (private mode, quota); fail quietly
  }
};

export const appendActivity = (
  recordId: string,
  entry: ActivityEntry,
): ActivityEntry[] => {
  const next = [...loadActivity(recordId), entry];
  saveActivity(recordId, next);
  return next;
};
