package handlers

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

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

func OrdenesProduccionListHandler(client client.IMediciones) httprouter.Handle {
	return func(w http.ResponseWriter, r *http.Request, ps httprouter.Params) {
		res, err := client.GetProductionOrders(r.Context(), types.GetProductionOrdersReq{
			Sender:    "mediciones-ui",
			Limit:     100,
			TimeStamp: time.Now().UTC().Format(time.RFC3339),
		})
		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)
	}
}

func OrdenProduccionHandler(client client.IMediciones) httprouter.Handle {
	return func(w http.ResponseWriter, r *http.Request, p httprouter.Params) {
		// convert to int
		po, err := strconv.Atoi(p.ByName("po"))
		if err != nil {
			http.Error(w, err.Error(), http.StatusInternalServerError)
			return
		}
		//
		res, err := client.GetProductionOrder(r.Context(), types.GetProductionOrderReq{
			Sender:    "mediciones-ui",
			PoNo:      po,
			TimeStamp: time.Now().UTC().Format(time.RFC3339),
		})
		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)
	}
}
