package canaconnect

import (
	"encoding/json"
	"net/http"
)

type Action[T any] struct {
	Read     func(r *http.Request) (T, error)
	Evaluate func(in T) (any, error)
}

func (a *Action[T]) ServeHTTP(w http.ResponseWriter, r *http.Request) {
	in, err := a.Read(r)
	if err != nil {
		http.Error(w, err.Error(), http.StatusBadRequest)
		return
	}
	out, err := a.Evaluate(in)
	if err != nil {
		http.Error(w, err.Error(), http.StatusInternalServerError)
		return
	}
	err = json.NewEncoder(w).Encode(out)
	if err != nil {
		panic(err)
	}
}
