package gateway

import (
	"strings"
	"sync"

	mntxv1 "github.com/tech/sendico/pkg/proto/gateway/mntx/v1"
	"google.golang.org/protobuf/proto"
)

type cardPayoutStore struct {
	mu      sync.RWMutex
	payouts map[string]*mntxv1.CardPayoutState
}

func newCardPayoutStore() *cardPayoutStore {
	return &cardPayoutStore{
		payouts: make(map[string]*mntxv1.CardPayoutState),
	}
}

func (s *cardPayoutStore) Save(p *mntxv1.CardPayoutState) {
	if p == nil {
		return
	}
	key := strings.TrimSpace(p.GetPayoutId())
	if key == "" {
		return
	}
	s.mu.Lock()
	defer s.mu.Unlock()
	s.payouts[key] = cloneCardPayoutState(p)
}

func (s *cardPayoutStore) Get(payoutID string) (*mntxv1.CardPayoutState, bool) {
	id := strings.TrimSpace(payoutID)
	if id == "" {
		return nil, false
	}
	s.mu.RLock()
	defer s.mu.RUnlock()
	val, ok := s.payouts[id]
	return cloneCardPayoutState(val), ok
}

func cloneCardPayoutState(p *mntxv1.CardPayoutState) *mntxv1.CardPayoutState {
	if p == nil {
		return nil
	}
	cloned := proto.Clone(p)
	if cp, ok := cloned.(*mntxv1.CardPayoutState); ok {
		return cp
	}
	return nil
}
