package cart

import (
	"fmt"

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

// mutation_initialize_checkout.go
//
// Registers the InitializeCheckout mutation.
// This mutation is invoked AFTER an external Klarna checkout session
// has been successfully created or updated. It persists the Klarna
// order reference / status and marks the cart as having a payment in progress.
//
// Behavior:
//   - Sets OrderReference to the Klarna order ID (overwriting if already set).
//   - Sets PaymentStatus to the current Klarna status.
//   - Sets / updates PaymentInProgress flag.
//   - Does NOT alter pricing or line items (so no totals recalculation).
//
// Validation:
//   - Returns an error if payload is nil.
//   - Returns an error if orderId is empty (integrity guard).
//
// Concurrency:
//   - Relies on upstream mutation serialization for a single grain. If
//     parallel checkout attempts are possible, add higher-level guards
//     (e.g. reject if PaymentInProgress already true unless reusing
//     the same OrderReference).

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

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