// Shared by the register (profile/education) and edit (profile/edit/education)
// pages so Going Back to the step never shows blank fields.

export interface Degree {
  degree: string;
  institute: string;
  field_of_study: string;
  passing_year: string;
}

export const EMPTY_DEGREE: Degree = {
  degree: "",
  institute: "",
  field_of_study: "",
  passing_year: "",
};

// What was last saved, kept for the tab session and keyed by the login so a
// different astrologer in the same tab never sees it.
const cacheKey = (token: string) => `astro_education_${token.slice(-12)}`;

export function readEducationCache(token: string): { ug: Degree; pg: Degree } | null {
  try {
    const raw = sessionStorage.getItem(cacheKey(token));

    return raw ? JSON.parse(raw) : null;
  } catch {
    return null;
  }
}

export function writeEducationCache(token: string, value: { ug: Degree; pg: Degree }) {
  try {
    sessionStorage.setItem(cacheKey(token), JSON.stringify(value));
  } catch {
    // storage unavailable — the profile read still restores it
  }
}

export function hasDegreeData(d: Degree | null | undefined): d is Degree {
  return !!d && Object.values(d).some((v) => String(v ?? "").trim() !== "");
}

// GET /astrologer/profile returns a flat `educations[]` with an `EducationType`
// ("UG"/"PG") discriminator and `specialization` (not the nested ug/pg keys or
// `field_of_study` the save payload uses). Tolerates other casings/keys, and a
// missing type (first row = UG, second = PG).
export function mapEducations(profile: any): { ug: Degree | null; pg: Degree | null } {
  const educations: any[] = profile?.educations ?? profile?.Educations ?? [];

  const typeOf = (e: any) =>
    String(e?.EducationType ?? e?.education_type ?? e?.type ?? "").toUpperCase();

  const anyTyped = educations.some((e) => typeOf(e));

  const toDegree = (e: any): Degree | null =>
    e
      ? {
          degree: e.degree ?? "",
          institute: e.institute ?? "",
          field_of_study: e.specialization ?? e.field_of_study ?? "",
          passing_year: e.passing_year?.toString() ?? "",
        }
      : null;

  return {
    ug: toDegree(educations.find((e) => typeOf(e) === "UG") ?? (anyTyped ? undefined : educations[0])),
    pg: toDegree(educations.find((e) => typeOf(e) === "PG") ?? (anyTyped ? undefined : educations[1])),
  };
}
