package main

import (
	"encoding/json"
	"fmt"
	"net/http"
	"strconv"
	"strings"

	"git.tornberg.me/go-cart-actor/pkg/cart"
	messages "git.tornberg.me/go-cart-actor/pkg/messages"
	"github.com/matst80/slask-finder/pkg/index"
)

// TODO make this configurable
func getBaseUrl(country string) string {
	// if country == "se" {
	// 	return "http://s10n-se:8080"
	// }
	if country == "no" {
		return "http://s10n-no.s10n:8080"
	}
	if country == "se" {
		return "http://s10n-se.s10n:8080"
	}
	return "http://localhost:8082"
}

func FetchItem(sku string, country string) (*index.DataItem, error) {
	baseUrl := getBaseUrl(country)
	res, err := http.Get(fmt.Sprintf("%s/api/by-sku/%s", baseUrl, sku))
	if err != nil {
		return nil, err
	}
	defer res.Body.Close()
	var item index.DataItem
	err = json.NewDecoder(res.Body).Decode(&item)
	return &item, err
}

func GetItemAddMessage(sku string, qty int, country string, storeId *string) (*messages.AddItem, error) {
	item, err := FetchItem(sku, country)
	if err != nil {
		return nil, err
	}
	return ToItemAddMessage(item, storeId, qty, country)
}

func ToItemAddMessage(item *index.DataItem, storeId *string, qty int, country string) (*messages.AddItem, error) {
	orgPrice, _ := getInt(item.GetNumberFieldValue(5)) // getInt(item.Fields[5])

	price, err := getInt(item.GetNumberFieldValue(4)) //Fields[4]
	if err != nil {
		return nil, err
	}

	stock := cart.StockStatus(0)
	centralStockValue, ok := item.GetStringFieldValue(3)
	if storeId == nil {
		if ok {
			if !item.Buyable {
				return nil, fmt.Errorf("item not available")
			}
			pureNumber := strings.Replace(centralStockValue, "+", "", -1)
			if centralStock, err := strconv.ParseInt(pureNumber, 10, 64); err == nil {
				stock = cart.StockStatus(centralStock)
			}
			if stock == cart.StockStatus(0) && item.SaleStatus == "TBD" {
				return nil, fmt.Errorf("no items available")
			}
		}
	} else {
		if !item.BuyableInStore {
			return nil, fmt.Errorf("item not available in store")
		}
		storeStock, ok := item.Stock.GetStock()[*storeId]
		if ok {
			stock = cart.StockStatus(storeStock)
		}

	}

	articleType, _ := item.GetStringFieldValue(1)   //.Fields[1].(string)
	outletGrade, ok := item.GetStringFieldValue(20) //.Fields[20].(string)
	var outlet *string
	if ok {
		outlet = &outletGrade
	}
	sellerId, _ := item.GetStringFieldValue(24)  // .Fields[24].(string)
	sellerName, _ := item.GetStringFieldValue(9) // .Fields[9].(string)

	brand, _ := item.GetStringFieldValue(2)      //.Fields[2].(string)
	category, _ := item.GetStringFieldValue(10)  //.Fields[10].(string)
	category2, _ := item.GetStringFieldValue(11) //.Fields[11].(string)
	category3, _ := item.GetStringFieldValue(12) //.Fields[12].(string)
	category4, _ := item.GetStringFieldValue(13) //Fields[13].(string)
	category5, _ := item.GetStringFieldValue(14) //.Fields[14].(string)

	return &messages.AddItem{
		ItemId:      uint32(item.Id),
		Quantity:    int32(qty),
		Price:       int64(price),
		OrgPrice:    int64(orgPrice),
		Sku:         item.GetSku(),
		Name:        item.Title,
		Image:       item.Img,
		Stock:       int32(stock),
		Brand:       brand,
		Category:    category,
		Category2:   category2,
		Category3:   category3,
		Category4:   category4,
		Category5:   category5,
		Tax:         getTax(articleType),
		SellerId:    sellerId,
		SellerName:  sellerName,
		ArticleType: articleType,
		Disclaimer:  item.Disclaimer,
		Country:     country,
		Outlet:      outlet,
		StoreId:     storeId,
		SaleStatus:  item.SaleStatus,
	}, nil
}

func getTax(articleType string) int32 {
	switch articleType {
	case "ZDIE":
		return 600
	default:
		return 2500
	}
}

func getInt(data float64, ok bool) (int, error) {
	if !ok {
		return 0, fmt.Errorf("invalid type")
	}
	return int(data), nil
}
