package handler

import (
	"context"
	"encoding/json"
	"fmt"
	"net/http"
	"mocksnow/components/views"
	"mocksnow/db/queries"
	"mocksnow/internal/utils"
)

func (h *Handler) RenderIncomingTable(w http.ResponseWriter, r *http.Request) {
	ctx := context.Background()

	h.Logger.Debug("Querying updates table")
	results, err := h.Database.Queries().ListIncoming(ctx)
	if err != nil {
		h.Logger.Error("Unable to query incoming table", "error", err)
		w.Header().Set("Content-Type", "application/json")
		w.WriteHeader(http.StatusInternalServerError)
		json.NewEncoder(w).Encode(map[string]string{
			"status":  "ERROR",
			"message": fmt.Sprintf("Unable to query incoming table: '%s'", err),
		})
		return
	}

	if len(results) == 0 {
		h.Logger.Error("Empty updates result")
		w.Header().Set("Content-Type", "application/json")
		w.WriteHeader(http.StatusInternalServerError)
		json.NewEncoder(w).Encode(map[string]string{
			"status":  "ERROR",
			"message": fmt.Sprintf("Empty updates result"),
		})
		return
	}

	views.IncomingTable(ConvertIncomingList(results)).Render(r.Context(), w)
}

// Converts a slice of Incoming to []IncomingRow
func ConvertIncomingList(list []queries.Incoming) []views.IncomingRow {
	rows := make([]views.IncomingRow, 0, len(list))
	for _, in := range list {
		var row views.IncomingRow
		utils.ConvertStruct(in, &row)
		rows = append(rows, row)
	}
	return rows
}
