import ky, { type KyInstance } from "ky";
import { useAuth } from "@/store/auth";

const API_BASE = import.meta.env.VITE_API_BASE ?? "/api/v1/mechanic";

export const api: KyInstance = ky.create({
  prefixUrl: API_BASE,
  timeout: 30_000,
  retry: { limit: 2, methods: ["get"] },
  hooks: {
    beforeRequest: [
      (request) => {
        const token = useAuth.getState().token;
        if (token) {
          request.headers.set("Authorization", `Bearer ${token}`);
        }
      },
    ],
    beforeError: [
      (error) => {
        if (error.response?.status === 401) {
          useAuth.getState().setToken(null);
        }
        return error;
      },
    ],
  },
});
