package wallet

import (
	"strings"

	"github.com/tech/sendico/gateway/chain/internal/service/gateway/shared"
	"github.com/tech/sendico/gateway/chain/storage/model"
	describablev1 "github.com/tech/sendico/pkg/proto/common/describable/v1"
	chainv1 "github.com/tech/sendico/pkg/proto/gateway/chain/v1"
	"google.golang.org/protobuf/types/known/timestamppb"
)

func toProtoManagedWallet(wallet *model.ManagedWallet) *chainv1.ManagedWallet {
	if wallet == nil {
		return nil
	}
	asset := &chainv1.Asset{
		Chain:           shared.ChainEnumFromName(wallet.Network),
		TokenSymbol:     wallet.TokenSymbol,
		ContractAddress: wallet.ContractAddress,
	}
	name := strings.TrimSpace(wallet.Name)
	if name == "" {
		name = strings.TrimSpace(wallet.Metadata["name"])
	}
	if name == "" {
		name = wallet.WalletRef
	}
	description := ""
	switch {
	case wallet.Description != nil:
		description = strings.TrimSpace(*wallet.Description)
	default:
		description = strings.TrimSpace(wallet.Metadata["description"])
	}
	desc := &describablev1.Describable{Name: name}
	if description != "" {
		desc.Description = &description
	}

	return &chainv1.ManagedWallet{
		WalletRef:       wallet.WalletRef,
		OrganizationRef: wallet.OrganizationRef,
		OwnerRef:        wallet.OwnerRef,
		Asset:           asset,
		DepositAddress:  wallet.DepositAddress,
		Status:          shared.ManagedWalletStatusToProto(wallet.Status),
		Metadata:        shared.CloneMetadata(wallet.Metadata),
		CreatedAt:       timestamppb.New(wallet.CreatedAt.UTC()),
		UpdatedAt:       timestamppb.New(wallet.UpdatedAt.UTC()),
		Describable:     desc,
	}
}

func toProtoWalletBalance(balance *model.WalletBalance) *chainv1.WalletBalance {
	if balance == nil {
		return nil
	}
	return &chainv1.WalletBalance{
		Available:       shared.CloneMoney(balance.Available),
		NativeAvailable: shared.CloneMoney(balance.NativeAvailable),
		PendingInbound:  shared.CloneMoney(balance.PendingInbound),
		PendingOutbound: shared.CloneMoney(balance.PendingOutbound),
		CalculatedAt:    timestamppb.New(balance.CalculatedAt.UTC()),
	}
}
