import type {
  HttpRequestConfig,
  HttpPluginOptions,
  HttpService,
} from "@c/http/httpTypes"
import type { AxiosRequestConfig } from "axios"
import type { FastifyInstance } from "fastify"
import axios from "axios"
import fastifyPlugin from "fastify-plugin"
import https from "https"

export default fastifyPlugin(
  async (fastify: FastifyInstance, options: HttpPluginOptions = {}) => {
    const client = axios.create({
      timeout: options.timeout || 30000,
      headers: {
        "Content-Type": "application/json",
        ...options.defaultHeaders,
      },
    })

    const createConfig = (
      config: HttpRequestConfig = {},
    ): AxiosRequestConfig => {
      if (config.ignoreSSL) {
        return {
          ...config,
          httpsAgent: new https.Agent({ rejectUnauthorized: false }),
        }
      }
      return config
    }

    const httpService: HttpService = {
      get: async <T = any>(url: string, config?: HttpRequestConfig) =>
        client.get<T>(url, createConfig(config)),

      post: async <T = any>(
        url: string,
        data?: any,
        config?: HttpRequestConfig,
      ) => client.post<T>(url, data, createConfig(config)),

      put: async <T = any>(
        url: string,
        data?: any,
        config?: HttpRequestConfig,
      ) => client.put<T>(url, data, createConfig(config)),

      delete: async <T = any>(url: string, config?: HttpRequestConfig) =>
        client.delete<T>(url, createConfig(config)),
    }

    fastify.decorate("http", httpService)
  },
)
