import { MedusaNextFunction } from '@medusajs/framework'
import { MedusaResponse, MiddlewareFunction } from '@medusajs/framework'
import { MedusaRequest } from '@medusajs/framework'

/**
 * Due to Medusa's `unlessPath` function bug, we need to use this function to skip middlewares for particular routes.
 * @param onPath - Regular expression or array of regular expressions to match against the base URL
 * @param middleware - The middleware function to execute
 * @param methods - Optional array of HTTP methods to match against. If not provided, matches all methods.
 */
export const unlessBaseUrl =
    (onPath: RegExp | RegExp[], middleware: MiddlewareFunction, methods?: string[]) =>
        (req: MedusaRequest, res: MedusaResponse, next: MedusaNextFunction) => {
            const methodMatches = !methods || methods.includes(req.method.toUpperCase())
            const paths = Array.isArray(onPath) ? onPath : [onPath]
            const pathMatches = paths.some(p => p.test(req.baseUrl))
            if (pathMatches && methodMatches) {
                return next()
            } else {
                return middleware(req, res, next)
            }
        }