import axios from "axios";
import { env } from "@/config/env";

/**
 * Shared axios instance configured with base URL and default timeout.
 */
console.log(env.apiBaseUrl,"checkAPI")
export const apiClient = axios.create({
  baseURL: env.apiBaseUrl,
  timeout: 15000,
  headers: {
    "Content-Type": "application/json",
  },
});

/** Error thrown for any non-2xx response or `{ success: false }` payload. */
export class ApiError extends Error {
  readonly status: number;
  readonly fieldErrors?: Record<string, unknown> | Array<unknown>;

  constructor(
    message: string,
    status: number,
    fieldErrors?: Record<string, unknown> | Array<unknown>,
  ) {
    super(message);
    this.name = "ApiError";
    this.status = status;
    this.fieldErrors = fieldErrors;
  }
}

interface ApiEnvelope {
  success?: boolean;
  message?: string;
  errors?: Record<string, unknown> | Array<unknown>;
}

interface RequestOptions {
  method?: "GET" | "POST" | "PUT" | "PATCH" | "DELETE";
  body?: unknown;
  signal?: AbortSignal;
  headers?: Record<string, string>;
}

/**
 * Typed wrapper around axios for the Sterling backend.
 */
export async function apiRequest<TResponse = ApiEnvelope>(
  path: string,
  { method = "GET", body, signal, headers }: RequestOptions = {},
): Promise<TResponse> {
  try {
    const response = await apiClient.request<TResponse & ApiEnvelope>({
      url: path,
      method,
      data: body,
      signal,
      headers,
    });

    if (response.data && response.data.success === false) {
      throw new ApiError(
        response.data.message ?? "Something went wrong.",
        response.status,
        response.data.errors,
      );
    }

    return response.data;
  } catch (error: unknown) {
    if (error instanceof ApiError) {
      throw error;
    }
    if (axios.isAxiosError(error) && error.response) {
      const responseData = error.response.data as ApiEnvelope | undefined;
      throw new ApiError(
        responseData?.message ?? error.message ?? "Request failed.",
        error.response.status,
        responseData?.errors,
      );
    }
    const message = error instanceof Error ? error.message : "Network error";
    throw new ApiError(message, 500);
  }
}

