package middleware

import (
	"errors"
	"net/http"

	licenseclient "qycw/go-server/internal/license"
	"qycw/go-server/internal/response"
)

// RequireCommercialLicense protects HTTP routes with the commercial HTTP feature.
func RequireCommercialLicense(eval *licenseclient.Evaluator) func(http.Handler) http.Handler {
	return RequireCommercialFeature(eval, licenseclient.FeatureHTTP)
}

func RequireCommercialFeature(eval *licenseclient.Evaluator, feature string) func(http.Handler) http.Handler {
	return func(next http.Handler) http.Handler {
		return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
			if eval == nil {
				writeCommercialError(w, licenseclient.ErrLicenseMissing)
				return
			}
			if err := eval.CheckFeature(feature); err != nil {
				writeCommercialError(w, err)
				return
			}
			next.ServeHTTP(w, r)
		})
	}
}

func writeCommercialError(w http.ResponseWriter, err error) {
	switch {
	case errors.Is(err, licenseclient.ErrLicenseMissing):
		response.Write(w, http.StatusForbidden, 6102, "请先配置商业授权码", nil)
	case errors.Is(err, licenseclient.ErrLicenseBlocked):
		response.Write(w, http.StatusForbidden, 6105, "商业授权已暂停或吊销，请联系服务商", nil)
	case errors.Is(err, licenseclient.ErrLicenseExpired):
		response.Write(w, http.StatusForbidden, 6104, "商业授权已过期，请续期", nil)
	case errors.Is(err, licenseclient.ErrLicenseGracePeriodExceeded):
		response.Write(w, http.StatusForbidden, 6110, "授权中心长时间未响应，请检查网络连接", nil)
	case errors.Is(err, licenseclient.ErrLicenseUnavailable):
		response.Write(w, http.StatusServiceUnavailable, 6110, "授权中心当前不可用", nil)
	case errors.Is(err, licenseclient.ErrLicenseFeatureMissing):
		response.Write(w, http.StatusForbidden, 6109, "当前商业授权未包含此功能", nil)
	case errors.Is(err, licenseclient.ErrLicenseClockInvalid):
		response.Write(w, http.StatusServiceUnavailable, 6111, "服务器时间异常，请校准系统时间后重试", nil)
	case errors.Is(err, licenseclient.ErrLicenseTampered):
		response.Write(w, http.StatusForbidden, 6103, "授权状态异常，请重新激活", nil)
	case errors.Is(err, licenseclient.ErrLicenseProtocol), errors.Is(err, licenseclient.ErrLicenseSequenceStale):
		response.Write(w, http.StatusForbidden, 6103, "授权响应校验失败，请联系服务商", nil)
	default:
		response.Write(w, http.StatusForbidden, 6100, "商业授权验证失败", nil)
	}
}
