package machines

import (
	"encoding/json"
	"jannex/admin-dashboard-backend/modules/config"
	"jannex/admin-dashboard-backend/modules/requestclient"
	"jannex/admin-dashboard-backend/modules/structs"
	"strconv"

	"git.ex.umbach.dev/Alex/roese-utils/rsutils"
	"github.com/gofiber/fiber/v2"
	"github.com/rs/zerolog/log"
)

type InvexApiStockListResponse struct {
	Results []struct {
		Notes      string
		Status     int
		Part       int
		PartDetail struct {
			Name      string
			Thumbnail string
		} `json:"part_detail"`
	}
}

func GetMachines(c *fiber.Ctx) error {
	var body structs.MachinesBody

	if err := rsutils.BodyParserHelper(c, &body); err != nil {
		return c.SendStatus(fiber.StatusBadRequest)
	}

	_, reqBody, err := requestclient.InvexApiRequestClient(fiber.MethodGet, config.Cfg.InvexAPI.Base+"/api/stock/?search=&offset=0&limit=50&location="+strconv.Itoa(body.Location)+"&part_detail=true&in_stock=0")

	if err != nil {
		log.Error().Msgf("Invex api request error: %s", err)
		return c.SendStatus(fiber.StatusInternalServerError)
	}

	// parse body as json
	var data InvexApiStockListResponse

	if err := json.Unmarshal(reqBody, &data); err != nil {
		log.Error().Msgf("Failed to unmarshal json, err: %s", err)
		return c.SendStatus(fiber.StatusInternalServerError)
	}

	var finalData InvexApiStockListResponse

	for _, item := range data.Results {
		if !contains(body.BlacklistParts, item.Part) {
			if len(body.WhitelistParts) == 0 || contains(body.WhitelistParts, item.Part) {
				finalData.Results = append(finalData.Results, item)
			}
		}
	}

	// send empty array if no results
	if len(finalData.Results) == 0 {
		return c.JSON([]string{})
	}

	return c.JSON(finalData.Results)
}

func contains(slice []int, item int) bool {
	for _, s := range slice {
		if s == item {
			return true
		}
	}
	return false
}
