"use client";
import { Fetcher } from "openapi-typescript-fetch";
import { getUser } from "./fetch";

interface GenericPaths {
  [path: string]: {
    [method: string]: any;
  };
}
const fetcher = Fetcher.for<GenericPaths>();
const BASE_URL = process.env.BACKEND_HOST || "http://127.0.0.1:8001";

// Configure the fetcher
fetcher.configure({
  baseUrl: BASE_URL,
  init: {
    headers: {
      "Content-Type": "application/json",
    },
  },
  use: [
    // Authentication middleware
    async (url, init, next) => {
      const user = getUser();
      if (user?.access_token) {
        init.headers = {
          ...init.headers,
          Authorization: `Bearer ${user.access_token}`,
        };
      }
      return next(url, init);
    },
    // Error handling middleware
    async (url, init, next) => {
      const response = await next(url, init);

      if (!response.ok) {
        // Handle authentication errors
        if (response.status === 401) {
          console.warn("Authentication failed - token may be expired");
          // You might want to trigger a redirect to login or token refresh here
        }

        // Log other errors
        console.error(`API Error: ${response.status} ${response.statusText}`, {
          url,
          method: init.method,
        });
      }

      return response;
    },
  ],
});

// Create your API methods
export const api = {
  tracks: {
    list: fetcher.path("/api/track/").method("get").create(),
    detail: fetcher.path("/api/track/{id}").method("get").create(),
  },
  artists: {
    list: fetcher.path("/api/artist").method("get").create(),
    detail: fetcher.path("/api/artist/{id}").method("get").create(),
  },
  albums: {
    list: fetcher.path("/api/album/").method("get").create(),
    detail: fetcher.path("/api/album/{id}").method("get").create(),
  },
  votes: {
    list: fetcher.path("/api/vote/").method("get").create(),
    detail: fetcher.path("/api/vote/{id}").method("get").create(),
    userVotes: fetcher.path("/api/user/{user_id}/votes").method("get").create(),
  },
  users: {
    list: fetcher.path("/api/user/").method("get").create(),
    detail: fetcher.path("/api/user/{id}").method("get").create(),
  },
  profiles: {
    detail: fetcher.path("/api/profile/{id}").method("get").create(),
    backgrounds: {
      list: fetcher.path("/api/profile/background").method("get").create(),
      detail: fetcher
        .path("/api/profile/background/{id}")
        .method("get")
        .create(),
    },
  },
};

export default api;
