package handlers

import (
	"encoding/json"
	"io"
	"net/http"
	"time"

	"git.espin.casa/albert/cml04-mediciones/internal/client"
	"git.espin.casa/albert/cml04-mediciones/internal/types"
	"github.com/julienschmidt/httprouter"
)

func TolerancesGetHandler(client client.IMediciones) httprouter.Handle {
	return func(w http.ResponseWriter, r *http.Request, ps httprouter.Params) {
		// request data struct
		type ToleranciaRequestData struct {
			Medida string `json:"medida"`
		}
		// request data holder
		req := &ToleranciaRequestData{}
		// read body request
		data, err := io.ReadAll(r.Body)
		if err != nil {
			http.Error(w, err.Error(), http.StatusInternalServerError)
			return
		}
		defer r.Body.Close()
		if err := json.Unmarshal(data, req); err != nil {
			http.Error(w, err.Error(), http.StatusInternalServerError)
			return
		}
		medida := req.Medida
		// request mediciones by po
		res, err := client.GetTolerancia(r.Context(), types.GetToleranciaReq{
			Sender:    "mediciones-ui",
			Medida:    medida,
			TimeStamp: time.Now().UTC().Format(time.RFC3339),
		})
		// handle error
		if err != nil {
			http.Error(w, err.Error(), http.StatusInternalServerError)
			return
		}
		// encode response
		resp, err := json.Marshal(&res)
		if err != nil {
			http.Error(w, err.Error(), http.StatusInternalServerError)
			return
		}
		// write header 200
		w.WriteHeader(http.StatusOK)
		// set header content type
		w.Header().Set("Content-type", "application/json")
		// write response
		w.Write(resp)

	}
}
