package authentication

import (
	"context"
	"net/http"

	d "github.com/karincake/dodol"
	rw "github.com/karincake/risoles"

	sc "simrs-vx/internal/lib/sync-credential"

	e "simrs-vx/internal/domain/sync-entities/authentication"
	is "simrs-vx/internal/infra/sync-cfg"
)

func NewGuardMW(next http.Handler) http.Handler {
	return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
		// check the data format
		input := e.CredentialDto{}
		if success := sc.CheckCredentialData(&input, r, w); !success {
			return
		}

		// check the validity
		if input.Source != is.O.NewSource || input.SecretKey != is.O.NewSecretKey {
			rw.WriteJSON(w, http.StatusUnauthorized, d.IS{"message": "invalid consumer credential"}, nil)
			return
		}

		ctx := context.WithValue(r.Context(), e.SyncKey{}, input)
		next.ServeHTTP(w, r.WithContext(ctx))
	})
}

func OldGuardMW(next http.Handler) http.Handler {
	return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
		// check the data format
		input := e.CredentialDto{}
		if success := sc.CheckCredentialData(&input, r, w); !success {
			return
		}

		// check the validity
		if input.Source != is.O.OldSource || input.SecretKey != is.O.OldSecretKey {
			rw.WriteJSON(w, http.StatusUnauthorized, d.IS{"message": "invalid consumer credential"}, nil)
			return
		}

		ctx := context.WithValue(r.Context(), e.SyncKey{}, input)
		next.ServeHTTP(w, r.WithContext(ctx))
	})
}
