/**
 * API Error Handler Middleware
 *
 * Logs the user out on 401 (auth is invalid). Does NOT log out on 403 —
 * that's an authorization/permission failure for an authenticated user
 * (e.g. a seller endpoint that requires `is_verified`), so kicking the
 * session out is wrong and used to silently sign users out of their own
 * store dashboard.
 */

import type { Middleware } from "../../src/api/types/runtime";

export const createAuthErrorMiddleware = (): Middleware => ({
  post: async (context) => {
    const response = context.response;

    if (response.status === 401) {
      console.warn("[API Error Handler] 401 Unauthorized — logging out user");
      if (typeof window !== "undefined") {
        window.location.href = "/logout";
      }
    }

    return response;
  },

  onError: async (context) => {
    console.error("[API Error Handler] Request failed:", context.error);
    return context.response;
  },
});
