package main

import (
	"fmt"

	messages "git.tornberg.me/go-cart-actor/pkg/messages"
)

// mutation_add_item.go
//
// Registers the AddItem cart mutation in the generic mutation registry.
// This replaces the legacy switch-based logic previously found in CartGrain.Apply.
//
// Behavior:
//   * Validates quantity > 0
//   * If an item with same SKU exists -> increases quantity
//   * Else creates a new CartItem with computed tax amounts
//   * Totals recalculated automatically via WithTotals()
//
// NOTE: Any future field additions in messages.AddItem that affect pricing / tax
// must keep this handler in sync.

func AddItem(g *CartGrain, m *messages.AddItem) error {
	if m == nil {
		return fmt.Errorf("AddItem: nil payload")
	}
	if m.Quantity < 1 {
		return fmt.Errorf("AddItem: invalid quantity %d", m.Quantity)
	}

	// Fast path: merge with existing item having same SKU
	if existing, found := g.FindItemWithSku(m.Sku); found {
		existing.Quantity += int(m.Quantity)
		return nil
	}

	g.mu.Lock()
	defer g.mu.Unlock()

	g.lastItemId++
	taxRate := 2500
	if m.Tax > 0 {
		taxRate = int(m.Tax)
	}
	taxAmountPerUnit := GetTaxAmount(m.Price, taxRate)

	g.Items = append(g.Items, &CartItem{
		Id:          g.lastItemId,
		ItemId:      int(m.ItemId),
		Quantity:    int(m.Quantity),
		Sku:         m.Sku,
		Name:        m.Name,
		Price:       m.Price,
		TotalPrice:  m.Price * int64(m.Quantity),
		TotalTax:    int64(taxAmountPerUnit * int64(m.Quantity)),
		Image:       m.Image,
		Stock:       StockStatus(m.Stock),
		Disclaimer:  m.Disclaimer,
		Brand:       m.Brand,
		Category:    m.Category,
		Category2:   m.Category2,
		Category3:   m.Category3,
		Category4:   m.Category4,
		Category5:   m.Category5,
		OrgPrice:    m.OrgPrice,
		ArticleType: m.ArticleType,
		Outlet:      m.Outlet,
		SellerId:    m.SellerId,
		SellerName:  m.SellerName,
		Tax:         int(taxAmountPerUnit),
		TaxRate:     taxRate,
		StoreId:     m.StoreId,
	})

	return nil
}
