import { ticketStatusBadgeClass } from "../constants/ticketStatus.js";
import { statusBadgeClass } from "../constants/swiDocumentStatus.js";

const DOCUMENT_ACTIONS = {
  created: {
    verb: "Registered",
    tone: "opened",
  },
  assigned: {
    verb: "Assigned",
    tone: "assigned",
  },
  completed: {
    verb: "Completed",
    tone: "completed",
  },
};

function parseTimestamp(value) {
  if (!value) return null;
  const date = new Date(value);
  return Number.isNaN(date.getTime()) ? null : date;
}

export function formatRelativeTime(value) {
  const date = parseTimestamp(value);
  if (!date) return "—";

  const now = Date.now();
  const diffMs = now - date.getTime();
  if (diffMs < 0) {
    return date.toLocaleDateString(undefined, { month: "short", day: "numeric" });
  }

  const minutes = Math.floor(diffMs / 60000);
  if (minutes < 1) return "Just now";
  if (minutes < 60) return `${minutes}m ago`;

  const hours = Math.floor(minutes / 60);
  if (hours < 24) return `${hours}h ago`;

  const days = Math.floor(hours / 24);
  if (days < 7) return `${days}d ago`;

  return date.toLocaleDateString(undefined, {
    month: "short",
    day: "numeric",
    year: date.getFullYear() !== new Date().getFullYear() ? "numeric" : undefined,
  });
}

function documentTitle(doc) {
  return (doc.document_name || "").trim() || `Document ${doc.document_id}`;
}

function pushDocumentEvent(items, doc, action, timestamp) {
  const meta = DOCUMENT_ACTIONS[action];
  if (!meta || !timestamp) return;

  const docKey = `${doc.document_id}-${doc.document_number}`;
  items.push({
    id: `doc-${action}-${docKey}`,
    kind: "document",
    action,
    verb: meta.verb,
    title: documentTitle(doc),
    subtitle: (doc.process_name || "").trim() || null,
    actor: null,
    timestamp,
    tone: meta.tone,
    badgeClass: statusBadgeClass(doc.document_status_id),
    meta: {
      documentId: doc.document_id,
      documentNumber: doc.document_number,
    },
  });
}

/**
 * Merge SWI document milestones and ticket log rows into one timeline.
 *
 * @param {{
 *   documents?: Array<Record<string, unknown>>,
 *   ticketLogs?: Array<Record<string, unknown>>,
 *   limit?: number,
 * }} options
 */
export function buildRecentActivity({
  documents = [],
  ticketLogs = [],
  limit = 12,
} = {}) {
  const items = [];

  for (const doc of documents) {
    pushDocumentEvent(items, doc, "created", doc.issued_at);

    if (doc.assigned_at && doc.assigned_to_user_id != null && doc.assigned_to_user_id !== "") {
      pushDocumentEvent(items, doc, "assigned", doc.assigned_at);
    }

    if (doc.completed_at) {
      pushDocumentEvent(items, doc, "completed", doc.completed_at);
    }
  }

  for (const log of ticketLogs) {
    const description = (log.description || "").trim();
    items.push({
      id: `ticket-log-${log.id}`,
      kind: "ticket",
      action: "updated",
      verb: log.status_type || "Updated",
      title: description || "Ticket updated",
      subtitle: [
        `Ticket #${log.ticket_id}`,
        log.ticket_type_name,
        log.user_name,
      ]
        .filter(Boolean)
        .join(" · "),
      actor: log.user_name || null,
      timestamp: log.created_at,
      tone:
        Number(log.status_id) === 3
          ? "completed"
          : Number(log.status_id) === 2
            ? "in-progress"
            : "opened",
      badgeClass: ticketStatusBadgeClass(log.status_id),
      meta: { ticketId: log.ticket_id },
    });
  }

  return items
    .filter((item) => parseTimestamp(item.timestamp))
    .sort(
      (a, b) =>
        parseTimestamp(b.timestamp).getTime() - parseTimestamp(a.timestamp).getTime()
    )
    .slice(0, Math.max(1, limit));
}
