// src/api/errors.ts

import axios from "axios";
import { ApiError } from "./types";

export function normalizeApiError(error: unknown): ApiError {
  if (!axios.isAxiosError(error)) {
    return {
      status: 0,
      message: "Unexpected error occurred",
    };
  }

  if (error.code === "ECONNABORTED") {
    return {
      status: 408,
      message: "Request timeout",
    };
  }

  if (!error.response) {
    return {
      status: 0,
      message: "Network error",
    };
  }

  const { status, data } = error.response;

  return {
    status,
    message:
      data?.message ||
      data?.error ||
      "Something went wrong",
    code: data?.code,
  };
}