import moment from "moment";
import { type AllOpportunitiesFiltersData } from "./opportunityFilters";

/**
 * The query string the opportunity lists send.
 *
 * The two lists had this written out twice, 30 lines each, differing in exactly
 * three keys — so a filter added to one list silently did nothing on the other.
 * It is pure and exported because what reaches the API is the part worth pinning:
 *
 *  - dates are reformatted to `YYYY-MM-DD`, because the pickers hand over ISO
 *    strings and the API rejects the time component;
 *  - the boolean filters are sent **only when true** (`|| undefined`). Sending
 *    `false` would filter *for* non-urgent opportunities rather than not
 *    filtering at all, which is a different and much smaller result set;
 *  - an unset age bound is omitted rather than sent as `null`, and `0` is a
 *    legitimate age that must survive — hence `typeof === "number"` and not a
 *    truthiness check.
 */
export function buildOpportunityListParams({
  page,
  limit,
  searchQuery,
  filters,
  isLearnServe,
}: {
  page: number;
  limit: number;
  searchQuery?: string;
  filters?: AllOpportunitiesFiltersData;
  /** Development opportunities take format filters; volunteering takes flags. */
  isLearnServe?: boolean;
}): Record<string, unknown> {
  const shared = {
    page,
    limit,
    search: searchQuery,
    start_date: filters?.startDate
      ? moment(filters.startDate).format("YYYY-MM-DD")
      : undefined,
    end_date: filters?.endDate
      ? moment(filters.endDate).format("YYYY-MM-DD")
      : undefined,
    tags: filters?.tags,
    location: filters?.location,
    gender: filters?.gender,
    min_age:
      typeof filters?.age?.[0] === "number" ? filters.age[0] : undefined,
    max_age:
      typeof filters?.age?.[1] === "number" ? filters.age[1] : undefined,
    opportunity_nationality: filters?.opportunity_nationality,
    match_my_interest: filters?.matchMyInterest || undefined,
    status: filters?.status,
    sort_by: filters?.sortBy || undefined,
  };

  if (isLearnServe) {
    return {
      ...shared,
      // The development list's «Type» options are `learning_type` choices; the
      // endpoint ignores `type` except to empty the list for «Volunteer».
      learning_type_id: filters?.type || undefined,
      in_person: filters?.isInPerson || undefined,
      online: filters?.isOnline || undefined,
    };
  }

  return {
    ...shared,
    type: filters?.type,
    is_relief: filters?.isRelief || undefined,
    is_emergency: filters?.isUrgent || undefined,
    is_supports_disabled: filters?.isSpecialNeed || undefined,
  };
}

/** The list endpoint each opportunity kind is served from. */
export const opportunityListEndpoint = (isLearnServe?: boolean): string =>
  isLearnServe ? "/learn-serve-opportunities/" : "/list-volunteer-opportunities/";
