import api from "./api";

import {
  RegisterPayload,
  VerifyOtpPayload,
} from "../types/auth";

import type {
  HoroscopeType,
  HoroscopeRequest,
} from "../types/horoscope";

import { getAuthToken } from "./token";

const HOROSCOPE_API =
  "https://api.astrology.togwe.com/api/user/horoscope";
  
export const registerUser = async (data: RegisterPayload) => {
  const { data: response } = await api.post("/register", data);
  return response;
};

export const sendLoginOtp = async (mobile: string) => {
  const { data } = await api.post("/login", { mobile });
  return data;
};

export const verifyLoginOtp = async (payload: VerifyOtpPayload) => {
  const { data } = await api.post(
    "/verify-login-otp",
    payload
  );

  return data;
};

export const resendOtp = async (userId: number) => {
  const { data } = await api.post(
    "/resend-otp",
    {
      userId,
    }
  );

  return data;
};

export const getUserHome = async (token: string) => {
  const response = await fetch("/api/get-user-home", {
    method: "GET",
    headers: {
      Authorization: `Bearer ${token}`,
    },
  });

  return response.json();
};
export const updateProfile = async (
  payload: any,
  token: string
) => {
  const { data } = await api.put(
    "/update-profile",
    payload,
    {
      headers: {
        Authorization: token,
      },
    }
  );

  return data;
};


export const getProfile = async (token: string) => {
  const { data } = await api.get("/profile", {
    headers: {
      Authorization: token,
    },
  });

  return data;
};

export const uploadProfileImage = async (
  file: File,
  token: string
) => {
  const formData = new FormData();

  formData.append("profile", file);

  // Deliberately plain fetch, not the shared `api` axios instance —
  // that instance forces "Content-Type: application/json" as a
  // default header, which stomps the multipart boundary axios
  // would otherwise set automatically for a FormData body.
  const response = await fetch("/api/profile/upload", {
    method: "POST",

    headers: {
      Authorization: token,
    },

    body: formData,
  });

  return response.json();
};


export const deleteAccount = async (
  id: number,
  token: string
) => {
  const { data } = await api.post(
    "/delete",
    {
      id,
    },
    {
      headers: {
        Authorization: token,
      },
    }
  );

  return data;
};



/*
|--------------------------------------------------------------------------
| Logout (POST /user/logout)
|--------------------------------------------------------------------------
|
| Confirmed real endpoint (Postman collection) — no body, just the
| bearer token. Used for both the header's "Logout" and "Logout From
| Other Devices" actions, and profile-settings' "Logout from all
| devices" — there's no separate "all devices" variant documented, so
| this is the same call for all of them; the caller is responsible for
| clearing local storage and redirecting afterward.
*/

export const logout = async (token: string) => {
  const { data } = await api.post(
    "/logout",
    {},
    {
      headers: {
        Authorization: token,
      },
    }
  );

  return data;
};

export const verifyMobileOtp = async (
  userId: number,
  otp: string,
  deviceToken?: string | null,
  deviceType: string = "Web"
) => {
  const { data } = await api.post(
    "/verify-mobile-otp",
    {
      userId,
      otp,
      ...(deviceToken ? { device_token: deviceToken, device_type: deviceType } : {}),
    }
  );

  return data;
};

export const verifyEmailOtp = async (
  userId: number,
  otp: string
) => {
  const { data } = await api.post(
    "/verify-email-otp",
    {
      userId,
      otp,
    }
  );

  return data;
};


export const getAstrologers = async (token: string) => {
  const { data } = await api.post(
    "/astrologers",
    {},
    {
      headers: {
        Authorization: token,
      },
    }
  );

  return data;
};



// ------------------------------------
// Horoscope API
// ------------------------------------

export async function fetchHoroscope(
  type: HoroscopeType,
  body: HoroscopeRequest
) {
  const token = await getAuthToken();

  if (!token) {
    return {
      authenticated: false,
      success: false,
      data: null,
    };
  }

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

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

      body: JSON.stringify(body),

      cache: "no-store",
    }
  );

  if (response.status === 401) {
    return {
      authenticated: false,
      success: false,
      data: null,
    };
  }

  const text = await response.text();

  let data: any;

  try {
    data = JSON.parse(text);
  } catch {
    console.error(
      "Horoscope API returned non-JSON:",
      text.substring(0, 500)
    );

    throw new Error(
      `Horoscope API returned invalid JSON. HTTP ${response.status}`
    );
  }

  if (!response.ok) {
    throw new Error(
      data?.message ||
        `Horoscope API failed: ${response.status}`
    );
  }

  return {
    authenticated: true,
    success: data?.status !== false,
    data,
  };
}