package cart

import (
	"encoding/json"
	"fmt"

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

func UpsertSubscriptionDetails(g *CartGrain, m *messages.UpsertSubscriptionDetails) error {
	if m == nil {
		return nil
	}

	// Create new subscription details when Id is nil.
	if m.Id == nil {
		// Validate JSON if provided.
		var meta json.RawMessage
		if m.Data != nil && len(m.Data.Value) > 0 {
			if !json.Valid(m.Data.Value) {
				return fmt.Errorf("subscription details invalid json")
			}
			meta = json.RawMessage(m.Data.Value)
		}

		id := MustNewCartId().String()
		g.SubscriptionDetails[id] = &SubscriptionDetails{
			Id:           id,
			OfferingCode: m.OfferingCode,
			SigningType:  m.SigningType,
			Meta:         meta,
		}
		return nil
	}

	// Update existing entry.
	existing, ok := g.SubscriptionDetails[*m.Id]
	if !ok {
		return fmt.Errorf("subscription details not found")
	}
	if m.OfferingCode != "" {
		existing.OfferingCode = m.OfferingCode
	}
	if m.SigningType != "" {
		existing.SigningType = m.SigningType
	}
	if m.Data != nil {
		// Only validate & assign if there is content; empty -> leave as-is.
		if len(m.Data.Value) > 0 {
			if !json.Valid(m.Data.Value) {
				return fmt.Errorf("subscription details invalid json")
			}
			existing.Meta = m.Data.Value
		}
	}
	return nil
}
