import moment from "moment";
import { hasOpportunityStarted, isOpportunityCancelled, opportunityEndsAt, opportunityStartsAt, parseKuwaitInstant, type ReviewSchedule } from "@/features/shared/clientReviewPolicy";

export interface ExclusionSource extends ReviewSchedule {
  registration_closes_at?: string | null;
  exclusion_closes_at?: string | null;
  can_exclude?: boolean | null;
  is_paid?: boolean | null;
}

/** Exclusion never extends into execution, including explicitly reopened volunteering. */
export function canExcludeRegistration(source: ExclusionSource | null | undefined, now = moment()): boolean {
  if (!source || source.is_paid === true || source.can_exclude === false || isOpportunityCancelled(source) || hasOpportunityStarted(source, now)) return false;
  const boundaries = [opportunityStartsAt(source), parseKuwaitInstant(source.registration_closes_at), parseKuwaitInstant(source.exclusion_closes_at)]
    .filter((date): date is moment.Moment => date !== null);
  return boundaries.length > 0 && now.isBefore(moment.min(boundaries));
}

/** Shared by row controls and the confirmation guard, not just the toolbar. */
export function canManageVolunteerRoles(source: ReviewSchedule | null | undefined, now = moment()): boolean {
  if (!source || isOpportunityCancelled(source)) return false;
  const end = opportunityEndsAt(source);
  return end !== null && now.isBefore(end);
}

