import moment from "moment";
import { hasOpportunityStarted, isOpportunityCancelled, opportunityStartsAt, type ReviewSchedule } from "./clientReviewPolicy";
import { canEditOrDelete, isViewerOrganizer, type OrganizerSource } from "./opportunityButtonState";

export type DeletionKind = "volunteer" | "learnserve" | "event";
export interface DeletionSource extends ReviewSchedule, OrganizerSource {
  id?: string | number;
  event_status?: string | null;
  deletion_status?: string | null;
  has_successful_payments?: boolean | null;
  has_active_payments?: boolean | null;
}

/** A delayed confirmation must never turn a review request into direct deletion. */
export function deletionAccessError({ id, type, requestOnly, source, userId }: {
  id: string; type: DeletionKind; requestOnly: boolean;
  source?: DeletionSource | null; userId?: string | number | null;
}, now = moment()): string | null {
  if (!source || !userId || String(source.id) !== id || !isViewerOrganizer(source, userId)) return "COMMON.PUBLISH_SOURCE_UNAVAILABLE";
  const schedule = type === "event" ? { ...source, opportunity_status: source.event_status ?? source.opportunity_status } : source;
  if (isOpportunityCancelled(schedule)) return "COMMON.CANCELLED";
  if (source.deletion_status === "pending") return "COMMON.DELETION_ALREADY_PENDING";
  if (type === "learnserve" && (source.has_successful_payments || source.has_active_payments)) return "COMMON.CANCELLATION_CONTACT_ADMIN";
  if (!opportunityStartsAt(schedule)) return "COMMON.PUBLISH_SOURCE_UNAVAILABLE";
  if (requestOnly) return !canEditOrDelete(schedule, now) && !hasOpportunityStarted(schedule, now)
    ? null : "COMMON.DELETION_REVIEW_WINDOW_CLOSED";
  return canEditOrDelete(schedule, now) ? null : "COMMON.EDIT_WINDOW_CLOSED";
}
