import axios, { AxiosInstance, AxiosRequestConfig, AxiosResponse } from 'axios';

class ApiService {
  private readonly axiosInstance: AxiosInstance;
  private readonly apiKey: string;

  constructor() {
    this.apiKey = import.meta.env.VITE_API_KEY || '';
    const baseURL = import.meta.env.VITE_API_BASE_URL || '';

    this.axiosInstance = axios.create({
      baseURL,
      timeout: 60_000,
      headers: { 'Content-Type': 'application/json' },
    });

    this.axiosInstance.interceptors.request.use((config) => {
      if (this.apiKey) {
        config.headers['apikey'] = this.apiKey;
      }
      return config;
    });

    this.axiosInstance.interceptors.response.use(
      (response) => response,
      (error) => {
        console.error('API Error:', {
          message: error.message,
          status: error.response?.status,
          data: error.response?.data,
        });
        return Promise.reject({
          message: error.response?.data?.message || error.message || 'Erro ao comunicar com o servidor',
          status: error.response?.status,
          data: error.response?.data,
        });
      }
    );
  }

  get<T = unknown>(url: string, config?: AxiosRequestConfig): Promise<AxiosResponse<T>> {
    return this.axiosInstance.get<T>(url, config);
  }

  post<T = unknown>(url: string, data?: unknown, config?: AxiosRequestConfig): Promise<AxiosResponse<T>> {
    return this.axiosInstance.post<T>(url, data, config);
  }

  postFormData<T = unknown>(url: string, formData: FormData, config?: AxiosRequestConfig): Promise<AxiosResponse<T>> {
    return this.axiosInstance.post<T>(url, formData, {
      ...config,
      headers: { ...config?.headers, 'Content-Type': 'multipart/form-data' },
    });
  }

  put<T = unknown>(url: string, data?: unknown, config?: AxiosRequestConfig): Promise<AxiosResponse<T>> {
    return this.axiosInstance.put<T>(url, data, config);
  }

  delete<T = unknown>(url: string, config?: AxiosRequestConfig): Promise<AxiosResponse<T>> {
    return this.axiosInstance.delete<T>(url, config);
  }

  getInstance(): AxiosInstance {
    return this.axiosInstance;
  }
}

export const apiService = new ApiService();
