import createClient, { type Middleware } from "openapi-fetch";

import type { paths } from "./schema";
import { redirectToLogin } from "./auth-redirect";

const onUnauthorized: Middleware = {
  async onResponse({ response }) {
    if (response.status === 401) {
      redirectToLogin();
    }

    return response;
  },
};

export const api = createClient<paths>({
  baseUrl: window.location.origin,
  credentials: "include",
});

api.use(onUnauthorized);
