/**
 * The order the volunteering save happens in.
 *
 * A publish or an edit is never one request. The steps and their order are a
 * contract with the backend — sponsors are synced against a record that must
 * already exist, and removed images are deleted only once the record has
 * accepted the new keep-set — so the sequence is extracted here, with its
 * operations injected, and asserted directly in
 * `tests/volunteerSubmitSteps.test.ts`. The hook keeps the toasts and the
 * navigation, which need React.
 */

export interface VolunteerUpdateSteps {
  /** PATCHes the record. Resolves with whether interest ids had to be dropped. */
  save: (data: FormData) => Promise<{ interestsDropped: boolean }>;
  deleteImages: (imageIds: number[]) => Promise<unknown>;
  syncSponsors: (organizationIds: string[]) => Promise<unknown>;
  /** Only called for a record the admin rejected. */
  resubmit: () => Promise<unknown>;
}

export interface VolunteerUpdateOutcome {
  interestsDropped: boolean;
  /** True once the record is back in the review queue. */
  resubmitted: boolean;
  /**
   * The save succeeded but putting it back in the queue did not. Reported
   * rather than thrown: the organizer's edit *was* stored, and telling them the
   * whole update failed would be wrong.
   */
  resubmitFailed: boolean;
}

/**
 * Editing an existing volunteering opportunity.
 *
 * Throws if the record, the image deletion or the sponsor sync fails — those
 * leave the opportunity in a state the organizer has to see. A failed resubmit
 * is reported in the outcome instead, for the reason above.
 */
export async function runVolunteerUpdate({
  formData,
  removedImageIds,
  sponsorIds,
  isRejected,
  steps,
}: {
  formData: FormData;
  removedImageIds: number[];
  sponsorIds: string[];
  /** `approval_status === "rejected"` — an edit alone does not requeue it. */
  isRejected: boolean;
  steps: VolunteerUpdateSteps;
}): Promise<VolunteerUpdateOutcome> {
  const { interestsDropped } = await steps.save(formData);

  // After the save, not before: the record has to have accepted the new
  // keep-set first, or a failed save would have deleted images it still holds.
  if (removedImageIds.length > 0) {
    await steps.deleteImages(removedImageIds);
  }

  // Always, including with an empty list — that is how a sponsor is removed.
  await steps.syncSponsors(sponsorIds);

  if (!isRejected) {
    return { interestsDropped, resubmitted: false, resubmitFailed: false };
  }

  try {
    await steps.resubmit();
    return { interestsDropped, resubmitted: true, resubmitFailed: false };
  } catch {
    return { interestsDropped, resubmitted: false, resubmitFailed: true };
  }
}

export interface VolunteerCreateSteps {
  create: (
    data: FormData
  ) => Promise<{ interestsDropped: boolean; opportunityId: string | null }>;
  syncSponsors: (opportunityId: string, organizationIds: string[]) => Promise<unknown>;
}

export interface VolunteerCreateOutcome {
  interestsDropped: boolean;
  /** Null when the response carried no id — nothing further is attempted. */
  opportunityId: string | null;
  /**
   * The sponsor sync's refusal, when the opportunity itself was created.
   * Returned rather than thrown: the record exists, so the caller must still
   * keep its id and clear the form, or a retry publishes a duplicate.
   */
  sponsorError?: unknown;
}

/**
 * Publishing a new volunteering opportunity.
 *
 * The sponsor sync needs the id the create returns, so it cannot be one
 * request. When the response carries no id the sync is skipped rather than
 * called with a blank one, which would 404 against every sponsor route.
 */
export async function runVolunteerCreate({
  formData,
  sponsorIds,
  steps,
}: {
  formData: FormData;
  sponsorIds: string[];
  steps: VolunteerCreateSteps;
}): Promise<VolunteerCreateOutcome> {
  const { interestsDropped, opportunityId } = await steps.create(formData);
  if (opportunityId == null) {
    return { interestsDropped, opportunityId: null };
  }
  try {
    await steps.syncSponsors(opportunityId, sponsorIds);
  } catch (sponsorError) {
    return { interestsDropped, opportunityId, sponsorError };
  }
  return { interestsDropped, opportunityId };
}

/**
 * Server keys that are not form field names. `new_opportunity_images_0` is
 * where `VolunteerAuthoring` reports a missing or non-square cover (PDF p.15);
 * without it that error reached only a toast, never the upload field.
 */
export const VOLUNTEER_FIELD_ALIASES: Record<string, string> = {
  location_url: "locationUrl",
  whatsapp_link: "link",
  new_opportunity_images_0: "opportunity_images",
};
