package middleware

import (
	"net/http"
	"net/url"
)

type (
	RedirectConfig struct {
		Skipper Skipper
		Code    int
	}

	redirectLogic func(u *url.URL) (url string, ok bool)
)

func Redirect(config RedirectConfig, redirect redirectLogic) Interceptor {
	if config.Skipper == nil {
		config.Skipper = DefaultSkipper
	}

	if config.Code == 0 {
		config.Code = http.StatusMovedPermanently
	}

	return func(w http.ResponseWriter, r *http.Request, next http.HandlerFunc) {
		if config.Skipper(r) {
			next(w, r)

			return
		}

		u := &url.URL{
			Scheme: "http",
			Host:   r.Host,
			Path:   r.RequestURI,
		}

		if r.TLS != nil {
			u.Scheme += "s"
		}

		if target, ok := redirect(u); ok {
			http.RedirectHandler(target, config.Code).ServeHTTP(w, r)
		} else {
			next(w, r)
		}
	}
}
