package cart

import (
	"fmt"

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

// mutation_order_created.go
//
// Registers the OrderCreated mutation.
//
// This mutation represents the completion (or state transition) of an order
// initiated earlier via InitializeCheckout / external Klarna processing.
// It finalizes (or updates) the cart's order metadata.
//
// Behavior:
//   - Validates payload non-nil and OrderId not empty.
//   - Sets (or overwrites) OrderReference with the provided OrderId.
//   - Sets PaymentStatus from payload.Status.
//   - Marks PaymentInProgress = false (checkout flow finished / acknowledged).
//   - Does NOT adjust monetary totals (no WithTotals()).
//
// Notes / Future Extensions:
//   - If multiple order completion events can arrive (e.g., retries / webhook
//     replays), this handler is idempotent: it simply overwrites fields.
//   - If you need to guard against conflicting order IDs, add a check:
//     if g.OrderReference != "" && g.OrderReference != m.OrderId { ... }
//   - Add audit logging or metrics here if required.
//
// Concurrency:
//   - Relies on the higher-level guarantee that Apply() calls are serialized
//     per grain. If out-of-order events are possible, embed versioning or
//     timestamps in the mutation and compare before applying changes.

func OrderCreated(g *CartGrain, m *messages.OrderCreated) error {
	if m == nil {
		return fmt.Errorf("OrderCreated: nil payload")
	}
	if m.OrderId == "" {
		return fmt.Errorf("OrderCreated: missing orderId")
	}

	g.OrderReference = m.OrderId
	g.PaymentStatus = m.Status
	g.PaymentInProgress = false
	return nil
}
