import { getAuthToken } from "./auth-token";
import { formatDate, getTodayDate, getTomorrowDate } from "./horoscope";

export type PanchangType =
  | "today"
  | "monthly"
  | "choghadiya"
  | "hora"
  | "festivals"
  | "sun-moon";

export { formatDate, getTodayDate, getTomorrowDate };

/*
|--------------------------------------------------------------------------
| Default Location
|--------------------------------------------------------------------------
|
| No geocoding is wired up yet (same limitation as the Free Kundli
| and Kundli Matching pages) — this is a fixed default location,
| editable as a display-only label.
|
*/

export const DEFAULT_PANCHANG_LOCATION = {
  label: "New Delhi, Delhi, India",
  latitude: 28.6139,
  longitude: 77.209,
  timezone: 5.5,
};

/*
|--------------------------------------------------------------------------
| Panchang Request
|--------------------------------------------------------------------------
*/

export async function panchangRequest(
  type: PanchangType,
  body: Record<string, any>
) {
  const token = getAuthToken();

  if (!token) {
    return {
      authenticated: false,
      success: false,
      data: null,
      message: "Please login first.",
    };
  }

  try {
    const response = await fetch(
      `/api/panchang/${type}`,
      {
        method: "POST",

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

        body: JSON.stringify(body),

        cache: "no-store",
      }
    );

    const result = await response.json();

    if (response.status === 401) {
      return {
        authenticated: false,
        success: false,
        data: null,
        message: result?.message || "Authentication expired.",
      };
    }

    if (!response.ok || result?.status !== true) {
      return {
        authenticated: true,
        success: false,
        data: null,
        message: result?.message || "Panchang request failed.",
      };
    }

    return {
      authenticated: true,
      success: true,
      data: result.data,
      message: result.message,
    };
  } catch (error) {
    console.error("Panchang request error:", error);

    return {
      authenticated: true,
      success: false,
      data: null,
      message: "Unable to connect to panchang API.",
    };
  }
}

/*
|--------------------------------------------------------------------------
| Request Body Builder
|--------------------------------------------------------------------------
*/

export interface PanchangLocation {
  latitude: number;
  longitude: number;
  timezone: number;
}

function buildBody(
  date: string,
  location: PanchangLocation,
  lang: string = "en"
) {
  return {
    date,
    time: "12:00",
    latitude: location.latitude,
    longitude: location.longitude,
    timezone: location.timezone,
    lang,
  };
}

/*
|--------------------------------------------------------------------------
| Lagna Chart Image
|--------------------------------------------------------------------------
|
| Same public GET /user/kundali/chart-image endpoint the Free Kundli
| page already calls directly from the client (no Authorization header
| needed — it's an <img src>, not a fetch call). Panchang has no birth
| time, so it uses noon for this date/location, matching buildBody()'s
| "time: 12:00" convention for every other panchang request.
|
*/

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

export function getPanchangChartImageUrl(
  date: string,
  location: PanchangLocation,
  style: "north" | "south" = "north",
  lang: string = "en",
): string {
  const query = new URLSearchParams({
    div: "D1",
    dob: date,
    lang,
    lat: location.latitude.toFixed(6),
    lon: location.longitude.toFixed(6),
    style,
    tob: "12:00",
    tz: String(location.timezone),
  });

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

/*
|--------------------------------------------------------------------------
| Today Panchang (tithi, nakshatra, yoga, karana, day timings)
|--------------------------------------------------------------------------
*/

export async function getTodayPanchang(
  date: string,
  location: PanchangLocation,
  lang: string = "en"
) {
  return panchangRequest("today", buildBody(date, location, lang));
}

/*
|--------------------------------------------------------------------------
| Sun & Moon Timings
|--------------------------------------------------------------------------
*/

export async function getSunMoonTimings(
  date: string,
  location: PanchangLocation,
  lang: string = "en"
) {
  return panchangRequest("sun-moon", buildBody(date, location, lang));
}

/*
|--------------------------------------------------------------------------
| Choghadiya Muhurta
|--------------------------------------------------------------------------
*/

export async function getChoghadiya(
  date: string,
  location: PanchangLocation,
  lang: string = "en"
) {
  return panchangRequest("choghadiya", buildBody(date, location, lang));
}

/*
|--------------------------------------------------------------------------
| Hora Muhurta
|--------------------------------------------------------------------------
*/

export async function getHora(
  date: string,
  location: PanchangLocation,
  lang: string = "en"
) {
  return panchangRequest("hora", buildBody(date, location, lang));
}

/*
|--------------------------------------------------------------------------
| Festivals & Vrats
|--------------------------------------------------------------------------
*/

export async function getFestivals(
  date: string,
  location: PanchangLocation,
  lang: string = "en"
) {
  return panchangRequest("festivals", buildBody(date, location, lang));
}
