package twitch

import (
	"bytes"
	"crypto/hmac"
	"crypto/rand"
	"crypto/sha256"
	"encoding/hex"
	"errors"
	"fmt"
	"io"
	"net/http"
	"strconv"
	"sync"

	"github.com/go-json-experiment/json"
)

// ErrVerificationFailed is the error returned when a webhook request does not
// verify correctly.
var ErrVerificationFailed = errors.New("Twitch webhook verification failed") //lint:ignore ST1005 Twitch is a proper noun

// Receive verifies a Twitch webhook request against the given secret
// and appends the request body to b.
// The maximum allowed request length is 1 MB.
func Receive(b, secret []byte, req *http.Request) ([]byte, error) {
	r := io.LimitReader(req.Body, 1<<20)
	w := bytes.NewBuffer(b)
	if _, err := io.Copy(w, r); err != nil {
		return nil, err
	}
	b = w.Bytes()

	h := hmac.New(sha256.New, secret)
	io.WriteString(h, req.Header.Get("Twitch-Eventsub-Message-Id"))
	io.WriteString(h, req.Header.Get("Twitch-Eventsub-Message-Timestamp"))
	h.Write(b)
	want := make([]byte, 0, len("sha256=")+sha256.Size*2)
	want = append(want, "sha256="...)
	sum := h.Sum(make([]byte, 0, sha256.Size))
	want = hex.AppendEncode(want, sum)

	got := req.Header.Get("Twitch-Eventsub-Message-Signature")
	if !hmac.Equal(want, []byte(got)) {
		return nil, fmt.Errorf("%w: computed %q, header has %q", ErrVerificationFailed, want, got)
	}
	return b, nil
}

// HandleChallenge responds to an EventSub verification challenge.
func HandleChallenge(w http.ResponseWriter, body []byte) error {
	var ev EventSub[struct{}]
	if err := json.Unmarshal(body, &ev); err != nil {
		return err
	}
	if ev.Challenge == "" {
		return errors.New("no challenge in body")
	}
	w.Header().Set("Content-Type", "text/plain")
	w.Header().Set("Content-Length", strconv.Itoa(len(ev.Challenge)))
	_, err := io.WriteString(w, ev.Challenge)
	return err
}

// Secret returns a process-wide secret for webhook subscriptions.
var Secret = sync.OnceValue(func() []byte {
	b := make([]byte, 32)
	rand.Read(b)
	return hex.AppendEncode(make([]byte, 0, 64), b)
})