package grpc

import (
	"context"

	walletv1 "hyapp.local/api/proto/wallet/v1"
	"hyapp/pkg/appcode"
	"hyapp/pkg/xerr"
	"hyapp/services/wallet-service/internal/domain/ledger"
)

// ListRechargeBills 暴露充值账单只读查询；后台 HTTP 层负责登录态和菜单权限。
func (s *Server) ListRechargeBills(ctx context.Context, req *walletv1.ListRechargeBillsRequest) (*walletv1.ListRechargeBillsResponse, error) {
	ctx = appcode.WithContext(ctx, req.GetAppCode())
	items, total, err := s.svc.ListRechargeBills(ctx, ledger.ListRechargeBillsQuery{
		AppCode:      req.GetAppCode(),
		UserID:       req.GetUserId(),
		SellerUserID: req.GetSellerUserId(),
		RegionID:     req.GetRegionId(),
		RechargeType: req.GetRechargeType(),
		Status:       req.GetStatus(),
		Keyword:      req.GetKeyword(),
		StartAtMS:    req.GetStartAtMs(),
		EndAtMS:      req.GetEndAtMs(),
		Page:         req.GetPage(),
		PageSize:     req.GetPageSize(),
	})
	if err != nil {
		return nil, xerr.ToGRPCError(err)
	}

	resp := &walletv1.ListRechargeBillsResponse{Bills: make([]*walletv1.RechargeBill, 0, len(items)), Total: total}
	for _, item := range items {
		resp.Bills = append(resp.Bills, rechargeBillToProto(item))
	}
	return resp, nil
}

func rechargeBillToProto(item ledger.RechargeBill) *walletv1.RechargeBill {
	return &walletv1.RechargeBill{
		AppCode:                item.AppCode,
		TransactionId:          item.TransactionID,
		CommandId:              item.CommandID,
		RechargeType:           item.RechargeType,
		Status:                 item.Status,
		ExternalRef:            item.ExternalRef,
		UserId:                 item.UserID,
		SellerUserId:           item.SellerUserID,
		SellerRegionId:         item.SellerRegionID,
		TargetRegionId:         item.TargetRegionID,
		PolicyId:               item.PolicyID,
		PolicyVersion:          item.PolicyVersion,
		CurrencyCode:           item.CurrencyCode,
		CoinAmount:             item.CoinAmount,
		UsdMinorAmount:         item.USDMinorAmount,
		ExchangeCoinAmount:     item.ExchangeCoinAmount,
		ExchangeUsdMinorAmount: item.ExchangeUSDMinorAmount,
		CreatedAtMs:            item.CreatedAtMS,
	}
}
