
export interface MatchPerson {
  name: string;
  gender: string;
  birth_date: string;
  birth_time: string;
  birth_place: string;
  latitude: number;
  longitude: number;
  timezone: number;
}

export interface MatchRequest {
  boy: MatchPerson;
  girl: MatchPerson;
  match_type: string;
  lang: string;
}

export interface SavedMatchPerson {
  name: string;
  gender: string;
  birthDate: string;
  birthTime: string;
  birthPlace: string;
}

export interface SavedMatch {
  localId: string;

  apiId?: number | string;

  boy: SavedMatchPerson;
  girl: SavedMatchPerson;

  match_type: string;

  response: any;

  /*
   * Per-guna (varna/vashya/tara/yoni/maitri/gan/bhakut/nadi)
   * breakdown from the "ashtakoot" endpoint. Optional — the
   * report still renders (score + doshas only) without it.
   */

  ashtakoot?: any;

  createdAt: string;
}

/*
|--------------------------------------------------------------------------
| Shared POST helper
|--------------------------------------------------------------------------
*/

async function postMatchEndpoint(
  endpoint: string,
  payload: MatchRequest
) {
  const token =
    typeof window !== "undefined"
      ? localStorage.getItem("token")
      : null;

  if (!token) {
    throw new Error("AUTH_REQUIRED");
  }

  const response = await fetch(
    endpoint,
    {
      method: "POST",

      headers: {
        "Content-Type": "application/json",
        Authorization: `Bearer ${token}`,
      },

      body: JSON.stringify(payload),

      cache: "no-store",
    }
  );

  let data: any = null;

  try {
    data = await response.json();
  } catch {
    data = null;
  }

  if (response.status === 401) {
    throw new Error("AUTH_REQUIRED");
  }

  if (!response.ok) {
    throw new Error(
      data?.message ||
      data?.error ||
      "Unable to match Kundli"
    );
  }

  return data;
}

/*
|--------------------------------------------------------------------------
| Generate Kundali Match
|--------------------------------------------------------------------------
*/

export async function generateKundaliMatch(
  payload: MatchRequest
) {
  /*
   * NOTE: the backend's "add" (save match) endpoint currently
   * fails with "Unknown column 'boyLatitude'" because of a
   * missing DB column, so we call "aggregate" instead — same
   * score + dosha report, but calculate-only (no server-side
   * persistence). Switch back to "/api/kundali-match/add" once
   * that's fixed.
   */

  return postMatchEndpoint("/api/kundali-match/aggregate", payload);
}

/*
|--------------------------------------------------------------------------
| Get Ashtakoot (per-guna) Breakdown
|--------------------------------------------------------------------------
*/

export async function getAshtakootBreakdown(
  payload: MatchRequest
) {
  return postMatchEndpoint("/api/kundali-match/ashtakoot", payload);
}

/*
|--------------------------------------------------------------------------
| Get current logged-in user's storage key
|--------------------------------------------------------------------------
*/

export function getKundaliMatchStorageKey(): string {
  if (typeof window === "undefined") {
    return "kundali_match_saved_guest";
  }

  const userData =
    localStorage.getItem("user");

  if (!userData) {
    return "kundali_match_saved_guest";
  }

  try {
    const user = JSON.parse(userData);

    const userId =
      user?.id ??
      user?.ID ??
      user?.user_id ??
      user?.userId;

    if (userId) {
      return `kundali_match_saved_${userId}`;
    }
  } catch {
    //
  }

  return "kundali_match_saved_guest";
}

/*
|--------------------------------------------------------------------------
| Get saved matches
|--------------------------------------------------------------------------
*/

export function getSavedMatches(): SavedMatch[] {
  if (typeof window === "undefined") {
    return [];
  }

  try {
    const key =
      getKundaliMatchStorageKey();

    const value =
      localStorage.getItem(key);

    if (!value) {
      return [];
    }

    const parsed =
      JSON.parse(value);

    return Array.isArray(parsed)
      ? parsed
      : [];
  } catch {
    return [];
  }
}

/*
|--------------------------------------------------------------------------
| Save Match
|--------------------------------------------------------------------------
*/

export function saveMatch(
  match: SavedMatch
) {
  if (typeof window === "undefined") {
    return;
  }

  const key =
    getKundaliMatchStorageKey();

  const existing =
    getSavedMatches();

  /*
   * Put newest match first
   */
  const updated = [
    match,
    ...existing,
  ];

  localStorage.setItem(
    key,
    JSON.stringify(updated)
  );
}

/*
|--------------------------------------------------------------------------
| Delete Match
|--------------------------------------------------------------------------
*/

export function deleteSavedMatch(
  localId: string
) {
  if (typeof window === "undefined") {
    return;
  }

  const key =
    getKundaliMatchStorageKey();

  const existing =
    getSavedMatches();

  const updated =
    existing.filter(
      (item) =>
        item.localId !== localId
    );

  localStorage.setItem(
    key,
    JSON.stringify(updated)
  );
}
