"use client";
import { Fetcher } from "openapi-typescript-fetch";
import { paths, components } from "muzak/data/types";
import { oidcConfig } from "muzak/config/auth";
import { User as OidcUser } from "oidc-client-ts";

export function getUser() {
  if (typeof window !== "undefined") {
    let oidcStorage = window?.sessionStorage.getItem(
      `oidc.user:${oidcConfig.authority}:${oidcConfig.client_id}`,
    );
    if (!oidcStorage) {
      oidcStorage = window?.localStorage.getItem(
        `oidc.user:${oidcConfig.authority}:${oidcConfig.client_id}`,
      );
    }
    if (!oidcStorage) {
      return null;
    }
    return OidcUser.fromStorageString(oidcStorage);
  }
}

const fetcher = Fetcher.for<paths>();
const BASE_URL = process.env.NEXT_PUBLIC_BACKEND_HOST!;
console.log("beest url", BASE_URL);

// Configure the fetcher
fetcher.configure({
  baseUrl: BASE_URL,
  init: {
    headers: {
      "Content-Type": "application/json",
    },
  },
  use: [
    // Add authentication token to request
    async (url, init, next) => {
      const user = getUser();
      if (user?.access_token) {
        (init.headers as any) = {
          ...init.headers,
          Authorization: `Bearer ${user.access_token}`,
          "Content-Type": "application/json",
        };
      }
      return next(url, init);
    },
    // Handle errors
    async (url, init, next) => {
      const response = await next(url, init);

      if (!response.ok) {
        if (response.status === 401) {
          console.warn("Authentication failed - token may be expired");
        }
        console.error(`API Error: ${response.status} ${response.statusText}`, {
          url,
          method: init.method,
        });
      }

      return response;
    },
  ],
});

export const api = {
  tracks: {
    list: fetcher.path("/api/track/").method("get").create(),
    detail: fetcher.path("/api/track/{id}").method("get").create(),
    vote: fetcher.path("/api/track/vote").method("get").create(),
    nominate: fetcher.path("/api/track/").method("post").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(),
  },
  users: {
    list: fetcher.path("/api/user/").method("get").create(),
  },
  profiles: {
    me: fetcher.path("/api/profile/me").method("get").create(),
  },
  sessions: {
    get: fetcher.path("/voting/session/{session_id}/").method("get").create(),
    info: fetcher
      .path("/voting/session/{session_id}/info")
      .method("get")
      .create(),
    list: fetcher.path("/voting/session/").method("get").create(),
  },
};

export type User = components["schemas"]["User"];
export type Track = components["schemas"]["Track"];
export type Album = components["schemas"]["Album"];
export type Profile = components["schemas"]["Profile"];
export type Session = components["schemas"]["Session"];

export default api;
