package cart

import (
	"slices"

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

func RemoveVoucher(g *CartGrain, m *messages.RemoveVoucher) error {
	if m == nil {
		return &actor.MutationError{
			Message:    "RemoveVoucher: nil payload",
			Code:       1003,
			StatusCode: 400,
		}
	}

	if !slices.ContainsFunc(g.Vouchers, func(v *Voucher) bool {
		return v.Id == m.Id
	}) {
		return &actor.MutationError{
			Message:    "voucher not applied",
			Code:       1004,
			StatusCode: 400,
		}
	}

	g.Vouchers = slices.DeleteFunc(g.Vouchers, func(v *Voucher) bool {
		return v.Id == m.Id
	})
	g.UpdateTotals()
	return nil
}

func AddVoucher(g *CartGrain, m *messages.AddVoucher) error {
	if m == nil {
		return &actor.MutationError{
			Message:    "AddVoucher: nil payload",
			Code:       1001,
			StatusCode: 400,
		}
	}

	if slices.ContainsFunc(g.Vouchers, func(v *Voucher) bool {
		return v.Code == m.Code
	}) {
		return &actor.MutationError{
			Message:    "voucher already applied",
			Code:       1002,
			StatusCode: 400,
		}
	}

	g.lastVoucherId++
	g.Vouchers = append(g.Vouchers, &Voucher{
		Id:    g.lastVoucherId,
		Code:  m.Code,
		Rules: m.VoucherRules,
		Value: m.Value,
	})
	g.UpdateTotals()
	return nil
}
