import { VerificationStatus } from "@/types/provider";
import type { ProviderDetail } from "@/types/provider";

export type ActivityKind =
  | "registered"
  | "verified"
  | "documentUploaded"
  | "documentApproved"
  | "documentRejected"
  | "memberJoined";

export interface ActivityEntry {
  id: string;
  kind: ActivityKind;
  /** ISO timestamp */
  at: string;
  /** Interpolation values for the entry's dictionary string */
  params?: Record<string, string>;
}

/**
 * Builds an activity timeline from the detail payload.
 *
 * There is no audit-log endpoint — the backend only stores timestamps on the
 * records themselves, so the history is derived from those: account creation
 * and verification, each document's upload and review, and when each team
 * member joined. That is genuinely everything the API exposes; anything richer
 * (who suspended an account and when) needs a backend audit log.
 *
 * Returned newest first.
 */
export function buildActivityTimeline(
  provider: ProviderDetail,
): ActivityEntry[] {
  const entries: ActivityEntry[] = [
    {
      id: `registered-${provider.id}`,
      kind: "registered",
      at: provider.createdAt,
    },
  ];

  if (provider.verifiedAt) {
    entries.push({
      id: `verified-${provider.id}`,
      kind: "verified",
      at: provider.verifiedAt,
    });
  }

  for (const document of provider.documents) {
    entries.push({
      id: `doc-upload-${document.id}`,
      kind: "documentUploaded",
      at: document.uploadedAt,
      params: { documentType: document.documentType },
    });

    // `verifiedAt` is stamped on every review action, including a reset back to
    // PENDING — only surface it as a decision when it actually is one.
    if (document.verifiedAt && document.status !== VerificationStatus.PENDING) {
      entries.push({
        id: `doc-review-${document.id}`,
        kind:
          document.status === VerificationStatus.APPROVED
            ? "documentApproved"
            : "documentRejected",
        at: document.verifiedAt,
        params: { documentType: document.documentType },
      });
    }
  }

  for (const member of provider.users) {
    entries.push({
      id: `member-${member.id}`,
      kind: "memberJoined",
      at: member.createdAt,
      params: { name: `${member.firstName} ${member.lastName}`.trim() },
    });
  }

  return entries.sort(
    (a, b) => new Date(b.at).getTime() - new Date(a.at).getTime(),
  );
}
