import axios from "axios";
import { getStoredLocale } from "@/lib/getLocale";

// Follow a user
export const followUser = async (token: string, followingId: string) => {
  try {
    const response = await axios.post(
      `${process.env.NEXT_PUBLIC_API_URL}/user/follow`,
      { following: followingId },
      {
        headers: {
          "Content-Type": "application/json",
          Authorization: `Bearer ${token}`,
          "Accept-Language": getStoredLocale(),
        },
      }
    );
    return response.data;
  } catch (error: any) {
    if (error?.response?.status === 401) {
      throw { ...error, isAuthError: true, status: 401, originalError: error };
    }
    throw error;
  }
};

// Unfollow a user
export const unfollowUser = async (token: string, followingId: string) => {
  try {
    const response = await axios.post(
      `${process.env.NEXT_PUBLIC_API_URL}/user/unfollow`,
      { following: followingId },
      {
        headers: {
          "Content-Type": "application/json",
          Authorization: `Bearer ${token}`,
          "Accept-Language": getStoredLocale(),
        },
      }
    );
    return response.data;
  } catch (error: any) {
    if (error?.response?.status === 401) {
      throw { ...error, isAuthError: true, status: 401, originalError: error };
    }
    throw error;
  }
};

// Helper to normalize pagination shapes coming from backend
const normalizePagination = (p: any) => {
  if (!p) return { total: 0, page: 1, limit: 20, totalPages: 1, filtered: 0 };
  const total = p.total ?? p.totalRecords ?? p.count ?? 0;
  const page = p.page ?? p.currentPage ?? 1;
  const limit = p.limit ?? p.perPage ?? 20;
  const totalPages =
    p.totalPages ?? p.pages ?? Math.max(1, Math.ceil(total / limit));
  const filtered = p.filtered ?? p.filteredCount ?? 0;
  return { total, page, limit, totalPages, filtered };
};

// Get follow lists
export const getFollowLists = async (
  token: string,
  limit = 20,
  page = 1,
  search?: string,
  type?: "follower" | "following"
) => {
  try {
    const params: any = { };
    if (search?.trim()) {
      params.search = search.trim(); 
    } else {
      params.limit = limit;
      params.page = page;
    }
    // if (type) params.type = type;

    const response = await axios.get(
      `${process.env.NEXT_PUBLIC_API_URL}/profile/get-followers-following`,
      {
        headers: {
          "Content-Type": "application/json",
          Authorization: `Bearer ${token}`,
          "Accept-Language": getStoredLocale(),
        },
        params,
      }
    );

    if (!response.data?.data) {
      throw new Error("Invalid response structure from server");
    }

    // Normalize pagination objects to a consistent shape
    const data = response.data;
    if (data.data?.followers) {
      data.data.followers.pagination = normalizePagination(
        data.data.followers.pagination
      );
    }
    if (data.data?.following) {
      data.data.following.pagination = normalizePagination(
        data.data.following.pagination
      );
    }

    return data;
  } catch (error: any) {
    if (error?.response?.status === 401) {
      throw { ...error, isAuthError: true, status: 401, originalError: error };
    }
    throw error;
  }
};

// Following list
export const getFollowingList = async (
  token: string,
  limit = 20,
  page = 1,
  search?: string
) => {
  const result = await getFollowLists(token, limit, page, search);
  return (
    result.data?.following || {
      data: [],
      pagination: { total: 0, page: 1, limit: 20, totalPages: 1, filtered: 0 },
    }
  );
};

// Followers list
export const getFollowersList = async (
  token: string,
  limit = 20,
  page = 1,
  search?: string
) => {
  const result = await getFollowLists(token, limit, page, search);
  return (
    result.data?.followers || {
      data: [],
      pagination: { total: 0, page: 1, limit: 20, totalPages: 1, filtered: 0 },
    }
  );
};
