import AsyncStorage from "@react-native-async-storage/async-storage";

const IS_WEB = typeof document !== "undefined";
const HOST = IS_WEB ? "localhost" : "10.0.2.2";
const API_BASE = `http://${HOST}:8000/api`;
export const STORAGE_BASE = `http://${HOST}:8000/storage`;

async function getHeaders() {
  const headers = { "Content-Type": "application/json" };
  const token = await AsyncStorage.getItem("token");
  if (token) headers.Authorization = `Bearer ${token}`;
  return headers;
}

async function request(path, options = {}) {
  const res = await fetch(`${API_BASE}${path}`, {
    headers: await getHeaders(),
    ...options,
  });

  if (res.status === 401) {
    await AsyncStorage.multiRemove(["token", "user"]);
    throw new Error("Unauthorized");
  }

  if (res.status === 204) return null;

  const data = await res.json();

  if (!res.ok) {
    throw new Error(data.message || "Request failed");
  }

  return data;
}

export const api = {
  async login(email, password) {
    return request("/login", {
      method: "POST",
      body: JSON.stringify({ email, password }),
    });
  },

  async register(name, email, password, password_confirmation) {
    return request("/register", {
      method: "POST",
      body: JSON.stringify({ name, email, password, password_confirmation }),
    });
  },

  async logout() {
    return request("/logout", { method: "POST" });
  },

  async getMe() {
    return request("/me");
  },

  async getAlbums() {
    return request("/albums");
  },

  async getAlbumById(id) {
    return request(`/albums/${id}`);
  },

  async getLikedTracks() {
    return request("/me/likes");
  },

  async likeTrack(trackId) {
    return request(`/tracks/${trackId}/like`, { method: "POST" });
  },

  async unlikeTrack(trackId) {
    return request(`/tracks/${trackId}/like`, { method: "DELETE" });
  },
};
