import { createError, getQuery } from "h3"
import { strapiFetch } from "@/utils/strapi.js"
import logger from "~~/server/utils/logger"

export function createStrapiProxyHandler({ strapiPath }) {
  return async (event) => {
    try {
      const query = getQuery(event)
      const qs = new URLSearchParams(query).toString()
      const path = qs ? `${strapiPath}?${qs}` : strapiPath

      return await strapiFetch(event, path)
    } catch (err) {
      logger.error("Strapi request failed", {
        label: "back-end",
        statusCode: err?.statusCode,
        statusMessage: err?.statusMessage,
        message: err?.message,
        data: err?.data,
        url: event?.path,
        method: event?.method,
      })

      throw createError({
        statusCode: err?.statusCode || 502,
        statusMessage:
          err?.statusMessage ||
          err?.message ||
          "Strapi request failed",
      })
    }
  }
}
