import moment from "moment";

/**
 * The achievements report's row model and the pure transforms behind it.
 *
 * Extracted so the de-duplication rule can be tested. It is the part most
 * likely to regress: the list endpoints overlap — a registered opportunity is
 * also an attended one once it ends — and each numbers its rows separately, so
 * identity has to be the title plus the year rather than the id.
 */
export interface ActivityRow {
  key: string;
  title_en: string;
  title_ar: string;
  year?: number;
  kind: "opportunity" | "event";
}

/**
 * The slice of `GET /account/` this report renders. The endpoint returns far
 * more (birth year, nationality, emergency contact, …) — only the identity the
 * report is meant to certify is read here.
 */
export interface AccountIdentity {
  profile_pic?: string | null;
  full_name?: string | null;
  first_name?: string | null;
  last_name?: string | null;
  email?: string | null;
  phone_number?: string | null;
  country_code?: string | null;
  civil_id?: string | null;
  gender_display?: { value_en?: string | null } | null;
}

export interface ListedActivity {
  id?: number | string;
  title_en?: string;
  title_ar?: string;
  start_date?: string | null;
  end_date?: string | null;
  due_date?: string | null;
}

/** The first of the given dates that parses, as a year. */
export const yearOf = (...dates: Array<string | null | undefined>) => {
  for (const date of dates) {
    if (!date) continue;
    const parsed = moment(date);
    if (parsed.isValid()) return parsed.year();
  }
  return undefined;
};

export const toActivityRows = (
  items: unknown,
  kind: ActivityRow["kind"],
  keyPrefix: string
): ActivityRow[] =>
  (Array.isArray(items) ? (items as ListedActivity[]) : []).map(
    (item, index) => ({
      key: `${keyPrefix}-${item?.id ?? index}`,
      title_en: item?.title_en ?? "",
      title_ar: item?.title_ar ?? "",
      year: yearOf(item?.start_date, item?.end_date, item?.due_date),
      kind,
    })
  );

/**
 * The activity table paginates client-side over the merged opportunity/event
 * list, so every source is pulled in one page rather than page-by-page.
 */
export const ACTIVITY_FETCH_LIMIT = 100;

/**
 * The list endpoints overlap (a registered opportunity is also an attended one
 * once it ends) and each numbers its rows separately, so identity is the
 * localized title plus the year rather than the id.
 */
export const dedupeRows = (rows: ActivityRow[]): ActivityRow[] =>
  Array.from(
    new Map(
      rows.map((row) => [`${row.title_en}|${row.title_ar}|${row.year}`, row])
    ).values()
  );

export const convertDecimalHoursToDisplay = (
  decimalHours: number | string | null | undefined
): string => {
  if (decimalHours === null || decimalHours === undefined) {
    return "0";
  }
  return decimalHours.toString();
};
