package middleware

import (
	"net/http"
	"strings"

	"haixun-backend/internal/config"
	app "haixun-backend/internal/library/errors"
	"haixun-backend/internal/library/errors/code"
	"haixun-backend/internal/response"
)

const WorkerSecretHeader = "X-Worker-Secret"

// WorkerSecretMiddleware enforces X-Worker-Secret on internal worker routes when
// InternalWorker.Secret is configured. Mounted via @server(middleware: WorkerSecret)
// in generate/api/worker_internal.api. When the secret is empty it passes through,
// preserving local-dev behaviour.
type WorkerSecretMiddleware struct {
	cfg config.InternalWorkerConf
}

func NewWorkerSecretMiddleware(cfg config.InternalWorkerConf) *WorkerSecretMiddleware {
	return &WorkerSecretMiddleware{cfg: cfg}
}

func (m *WorkerSecretMiddleware) Handle(next http.HandlerFunc) http.HandlerFunc {
	return func(w http.ResponseWriter, r *http.Request) {
		secret := strings.TrimSpace(m.cfg.Secret)
		if secret != "" && r.Header.Get(WorkerSecretHeader) != secret {
			response.Write(r.Context(), w, nil, app.For(code.Auth).AuthUnauthorized("invalid worker secret"))
			return
		}
		next(w, r)
	}
}
