package main

import (
	"context"
	"log"
	"strconv"
	"strings"
	"sync"

	"git.tornberg.me/mats/go-redis-inventory/pkg/inventory"
	"github.com/matst80/slask-finder/pkg/types"
	"github.com/redis/go-redis/v9"
)

type StockHandler struct {
	rdb                 *redis.Client
	ctx                 context.Context
	svc                 inventory.RedisInventoryService
	MainStockLocationID inventory.LocationID
}

func (s *StockHandler) HandleItem(item types.Item, wg *sync.WaitGroup) {
	wg.Go(func() {
		ctx := s.ctx
		pipe := s.rdb.Pipeline()
		centralStockString, ok := item.GetStringFieldValue(3)
		if !ok {
			centralStockString = "0"
		}
		centralStockString = strings.Replace(centralStockString, "+", "", -1)
		centralStockString = strings.Replace(centralStockString, "<", "", -1)
		centralStockString = strings.Replace(centralStockString, ">", "", -1)
		centralStock, err := strconv.ParseInt(centralStockString, 10, 64)

		if err != nil {
			log.Printf("unable to parse central stock for item %s: %v", item.GetSku(), err)
			centralStock = 0
		} else {
			s.svc.UpdateInventory(ctx, pipe, inventory.SKU(item.GetSku()), s.MainStockLocationID, int64(centralStock))
		}
		for id, value := range item.GetStock() {
			s.svc.UpdateInventory(ctx, pipe, inventory.SKU(item.GetSku()), inventory.LocationID(id), int64(value))
		}
		_, err = pipe.Exec(ctx)
		if err != nil {
			log.Printf("unable to update stock: %v", err)
		}
	})
}
