const API_URL = import.meta.env.VITE_API_URL || "/api";

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

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

  if (res.status === 401) {
    localStorage.removeItem("token");
    localStorage.removeItem("user");
    window.location.href = "/login";
    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 getAlbums() {
    return request("/albums");
  },

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

  async addAlbum(data) {
    return request("/albums", {
      method: "POST",
      body: JSON.stringify(data),
    });
  },

  async deleteAlbum(id) {
    return request(`/albums/${id}`, { method: "DELETE" });
  },

  async addTrack(data) {
    return request("/tracks", {
      method: "POST",
      body: JSON.stringify(data),
    });
  },

  async updateTrack(id, data) {
    return request(`/tracks/${id}`, {
      method: "PUT",
      body: JSON.stringify(data),
    });
  },

  async deleteTrack(id) {
    return request(`/tracks/${id}`, { method: "DELETE" });
  },

  async reorderTracks(albumId, positions) {
    return request(`/albums/${albumId}/tracks/reorder`, {
      method: "PUT",
      body: JSON.stringify({ positions }),
    });
  },

  async uploadImage(file) {
    const formData = new FormData();
    formData.append("file", file);
    const res = await fetch(`${API_URL}/upload/image`, {
      method: "POST",
      headers: { Authorization: `Bearer ${localStorage.getItem("token")}` },
      body: formData,
    });
    if (!res.ok) throw new Error("Upload failed");
    return res.json();
  },

  async uploadAudio(file) {
    const formData = new FormData();
    formData.append("file", file);
    const res = await fetch(`${API_URL}/upload/audio`, {
      method: "POST",
      headers: { Authorization: `Bearer ${localStorage.getItem("token")}` },
      body: formData,
    });
    if (!res.ok) throw new Error("Upload failed");
    return res.json();
  },

  async getArtists() {
    return request("/artists");
  },

  async addArtist(data) {
    return request("/artists", {
      method: "POST",
      body: JSON.stringify(data),
    });
  },

  async getGenres() {
    return request("/genres");
  },

  async addGenre(data) {
    return request("/genres", {
      method: "POST",
      body: JSON.stringify(data),
    });
  },

  async updateAlbum(id, data) {
    return request(`/albums/${id}`, {
      method: "PUT",
      body: JSON.stringify(data),
    });
  },

  async getUsers() {
    return request("/users");
  },

  async updateUser(id, data) {
    return request(`/users/${id}`, {
      method: "PUT",
      body: JSON.stringify(data),
    });
  },

  async deleteUser(id) {
    return request(`/users/${id}`, { method: "DELETE" });
  },
};
