package server

import (
	"context"
	"crypto"
	"fmt"
	"net/http"

	"github.com/common-fate/httpsig"
	"github.com/common-fate/httpsig/inmemory"
)

func Start(publicKey crypto.PublicKey, isCaddyAuth bool) error {
	keyDir := InMemoryDirectory{
		records: map[string]KeyEntry{},
	}

	keyId := "test-id"

	keyDir.records[keyId] = KeyEntry{
		alg:       "ed25519",
		publicKey: publicKey,
		userId:    "test_user",
	}

	mux := http.NewServeMux()

	verifier := httpsig.Middleware(httpsig.MiddlewareOpts{
		NonceStorage: inmemory.NewNonceStorage(),
		KeyDirectory: &keyDir,
		Tag:          "auth",
		Scheme:       "http",
		Authority:    "localhost:8080",

		OnValidationError: func(ctx context.Context, err error) {
			fmt.Printf("validation error: %s\n", err)
		},

		OnDeriveSigningString: func(ctx context.Context, stringToSign string) {
			fmt.Printf("string to sign:\n%s\n", stringToSign)
		},
	})

	verifyHandler := verifier(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
		attr := httpsig.AttributesFromContext(r.Context()).(string)

		if isCaddyAuth {
			w.Header().Add("Remote-User", attr)
		} else {
			msg := fmt.Sprintf("hello, %s!", attr)
			w.Write([]byte(msg))
		}
	}))

	var handler http.Handler

	if isCaddyAuth {
		handler = rewriteHeaders(verifyHandler)
	} else {
		handler = verifyHandler
	}

	mux.Handle("/", handler)

	err := http.ListenAndServe("localhost:8080", mux)

	return err
}