package auth

import (
	"context"
	"errors"
	"strings"

	"connectrpc.com/connect"
)

func NewPSKInterceptor(psk string) connect.UnaryInterceptorFunc {
	return func(next connect.UnaryFunc) connect.UnaryFunc {
		return func(ctx context.Context, req connect.AnyRequest) (connect.AnyResponse, error) {
			if req.Spec().IsClient {
				return nil, errors.New("Serverside PSKInterceptor intercepted on the client.")
			} else if req.Header().Get("token-header") == "" {
				// No Auth Token Present
				return nil, errors.New("No Auth Token present!")
			} else if !strings.HasPrefix(req.Peer().Addr, "192.168.143") {
				// Not from trusted subnet
				return nil, errors.New("Request from untrusted subnet")
			} else {
				authToken := req.Header().Get("token-header")

				if authToken != "MWE4MWQ5NDY2OWM1NGI4ZDhmNDNkZDc2Y2M5M2IyYThlMTIzZjNmNzY4ZTg2NDA2MGRjZWFjZjI3M2MxYTkzNDFhZDM5YjA0NmYzYjZiODEzZjNjNDZiYjhkMGU0OTdlOGNkN2FmMDFiYjczMWJmNDZhMGI4Yjk0OTZhNQo=" {
					return nil, errors.New("Invalid auth-token")
				}

				return next(ctx, req)
			}
		}
	}
}
