import moment from "moment";
import { hasOpportunityEnded, hasOpportunityStarted, type ReviewSchedule } from "@/features/shared/clientReviewPolicy";

export interface EventSchedule extends ReviewSchedule { event_status?: string | null }

/** Events use the same Kuwait schedule; old date-only registration deadlines are retired. */
export function eventSchedule(event: EventSchedule): ReviewSchedule {
  return { ...event, opportunity_status: event.event_status ?? event.opportunity_status };
}

export function eventStateLabel(event: EventSchedule, now = moment()): string | null {
  const schedule = eventSchedule(event);
  if (schedule.opportunity_status === "cancelled") return "COMMON.CANCELLED";
  if (hasOpportunityEnded(schedule, now)) return "COMMON.ENDED";
  if (hasOpportunityStarted(schedule, now)) return "COMMON.STARTED";
  return null;
}

export function eventExternalRegistrationLink(event: {
  participation_type_display?: { value_en?: string | null } | null;
  registration_link?: string | null;
}): string | null {
  return event.participation_type_display?.value_en === "Free Event" ? null : event.registration_link?.trim() || null;
}

/**
 * A typed link as the API stores it: the form accepts `www.example.com`
 * (`YupFlexibleUrl` / `YupOptionalUrl` add the scheme only to *check* it), but
 * Laravel's `url` rule refuses a value without one — so the scheme is added
 * before sending, instead of failing the save on a value the form accepted.
 */
export function withWebScheme(value: string | null | undefined): string {
  const trimmed = (value ?? "").trim();
  if (!trimmed) return "";
  return /^[a-z][a-z\d+.-]*:/i.test(trimmed) ? trimmed : `https://${trimmed}`;
}

/** An http(s) URL to open for a stored external link, or null (never a relative or script URL). */
export function externalHref(link: string | null | undefined): string | null {
  const value = withWebScheme(link);
  if (!value) return null;
  try {
    const url = new URL(value);
    return url.protocol === "https:" || url.protocol === "http:" ? url.href : null;
  } catch {
    return null;
  }
}

/**
 * A deletion request already waits for administration. The website payload
 * carries no `deletion_status`; the server refuses both `can_delete` and
 * `can_request_deletion` only then (before the start, not cancelled). Reading
 * both keeps a page opened before the 24 h cutoff — where `can_delete` was
 * still true — from claiming a pending request once the cutoff passes.
 */
export function isEventDeletionRequestPending(event: { can_delete?: boolean; can_request_deletion?: boolean }): boolean {
  return event.can_delete === false && event.can_request_deletion === false;
}
