
const KUNDALI_API_BASE =
  process.env.NEXT_PUBLIC_API_BASE_URL || "https://api.astrology.togwe.com/api";

/*
|--------------------------------------------------------------------------
| Chart image URL — same no-auth GET /user/kundali/chart-image endpoint
| app/lib/panchang.ts's getPanchangChartImageUrl already uses (confirmed
| live there: needs no Authorization header, used directly as an
| <img src>). That helper hardcodes tob="12:00" since Panchang has no
| birth time; this one takes a real time of birth, for callers that
| have one (e.g. the astrologer chat page's Kundli-at-a-glance modal).
|--------------------------------------------------------------------------
*/

export function getKundaliChartImageUrl(
  div: string,
  birthDate: string,
  birthTime: string,
  location: { latitude: number; longitude: number; timezone: number },
  style: "north" | "south" = "north",
  lang: string = "en",
): string {
  const query = new URLSearchParams({
    div,
    dob: birthDate,
    lang,
    lat: location.latitude.toFixed(6),
    lon: location.longitude.toFixed(6),
    style,
    tob: birthTime,
    tz: String(location.timezone),
  });

  return `${KUNDALI_API_BASE}/user/kundali/chart-image?${query.toString()}`;
}

export interface KundaliPerson {
  id: number;
  lang: string;
  name: string;
  gender: string;
  birthDate: string;
  birthTime: string;
  birthPlace: string;
  latitude: number;
  longitude: number;
  timezone: number;
  pdf_type: string;
  match_type: string;
  forMatch: boolean;
}

export interface KundaliRequest {
  amount: number;
  is_match: boolean;
  kundali: KundaliPerson[];
}

export interface SavedKundali {
  localId: string;

  apiId?: number | string;

  name: string;
  gender: string;
  birthDate: string;
  birthTime: string;
  birthPlace: string;

  latitude: number;
  longitude: number;
  timezone: number;

  pdf_type: string;
  match_type: string;

  response: any;

  createdAt: string;
}

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

// `authToken`, when passed, is used verbatim instead of the end-user
// `token` key — the astrologer chat page's Kundli-at-a-glance modal
// calls this with the astrologer's own `astrologerToken` (per explicit
// direction: this endpoint is confirmed to accept it, even though it's
// namespaced under /user/kundali/add and the astrologer app has no
// end-user session of its own).
export async function generateKundali(
  payload: KundaliRequest,
  authToken?: string,
) {
  const token =
    authToken ??
    (typeof window !== "undefined"
      ? localStorage.getItem("token")
      : null);

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

  const response = await fetch(
    "/api/kundali/add",
    {
      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 generate Kundali"
    );
  }

  return data;
}

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

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

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

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

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

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

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

  return "kundali_saved_guest";
}

/*
|--------------------------------------------------------------------------
| Get saved Kundlis
|--------------------------------------------------------------------------
*/

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

  try {
    const key =
      getKundaliStorageKey();

    const value =
      localStorage.getItem(key);

    if (!value) {
      return [];
    }

    const parsed =
      JSON.parse(value);

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

/*
|--------------------------------------------------------------------------
| Save Kundali
|--------------------------------------------------------------------------
*/

export function saveKundali(
  kundali: SavedKundali
) {
  if (typeof window === "undefined") {
    return;
  }

  const key =
    getKundaliStorageKey();

  const existing =
    getSavedKundalis();

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

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

/*
|--------------------------------------------------------------------------
| Delete Kundali
|--------------------------------------------------------------------------
*/

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

  const key =
    getKundaliStorageKey();

  const existing =
    getSavedKundalis();

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

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