package transfer

import (
	"github.com/tech/sendico/gateway/tron/shared"
	"github.com/tech/sendico/gateway/tron/storage/model"
	chainv1 "github.com/tech/sendico/pkg/proto/gateway/chain/v1"
	"google.golang.org/protobuf/types/known/timestamppb"
)

func toProtoTransfer(transfer *model.Transfer) *chainv1.Transfer {
	if transfer == nil {
		return nil
	}
	destination := &chainv1.TransferDestination{}
	if transfer.Destination.ManagedWalletRef != "" {
		destination.Destination = &chainv1.TransferDestination_ManagedWalletRef{ManagedWalletRef: transfer.Destination.ManagedWalletRef}
	} else if transfer.Destination.ExternalAddress != "" {
		destination.Destination = &chainv1.TransferDestination_ExternalAddress{ExternalAddress: transfer.Destination.ExternalAddress}
	}
	destination.Memo = transfer.Destination.Memo

	protoFees := make([]*chainv1.ServiceFeeBreakdown, 0, len(transfer.Fees))
	for _, fee := range transfer.Fees {
		protoFees = append(protoFees, &chainv1.ServiceFeeBreakdown{
			FeeCode:     fee.FeeCode,
			Amount:      shared.CloneMoney(fee.Amount),
			Description: fee.Description,
		})
	}

	asset := &chainv1.Asset{
		Chain:           shared.ChainEnumFromName(transfer.Network),
		TokenSymbol:     transfer.TokenSymbol,
		ContractAddress: transfer.ContractAddress,
	}

	return &chainv1.Transfer{
		TransferRef:     transfer.TransferRef,
		IdempotencyKey:  transfer.IdempotencyKey,
		OrganizationRef: transfer.OrganizationRef,
		IntentRef:       transfer.IntentRef,
		SourceWalletRef: transfer.SourceWalletRef,
		Destination:     destination,
		Asset:           asset,
		RequestedAmount: shared.MonenyToProto(transfer.RequestedAmount),
		NetAmount:       shared.MonenyToProto(transfer.NetAmount),
		Fees:            protoFees,
		Status:          shared.TransferStatusToProto(transfer.Status),
		TransactionHash: transfer.TxHash,
		FailureReason:   transfer.FailureReason,
		CreatedAt:       timestamppb.New(transfer.CreatedAt.UTC()),
		UpdatedAt:       timestamppb.New(transfer.UpdatedAt.UTC()),
	}
}
