package paymentconfig

import (
	"time"

	"hfb_sys/backend/internal/model"
)

// toDTO 转换为 DTO
func (r *Repository) toDTO(item model.PaymentMerchantConfig, includeSecret bool) (ConfigDTO, error) {
	dto := ConfigDTO{
		ID:                item.ID,
		Name:              item.Name,
		Provider:          item.Provider,
		MerchantID:        item.MerchantID,
		GatewayURL:        item.GatewayURL,
		NotifyURL:         item.NotifyURL,
		JumpURL:           item.JumpURL,
		PayWay:            item.PayWay,
		JSPayFlag:         item.JSPayFlag,
		SignType:          item.SignType,
		ExtraConfig:       item.ExtraConfig,
		IsDefault:         item.IsDefault,
		Status:            item.Status,
		Environment:       item.Environment,
		BusinessTags:      item.BusinessTags,
		TotalTransactions: item.TotalTransactions,
		TotalAmountCent:   item.TotalAmountCent,
		CreatedBy:         item.CreatedBy,
		UpdatedBy:         item.UpdatedBy,
		CreatedAt:         item.CreatedAt.Format(time.RFC3339),
		UpdatedAt:         item.UpdatedAt.Format(time.RFC3339),
	}

	if item.LastUsedAt != nil {
		s := item.LastUsedAt.Format(time.RFC3339)
		dto.LastUsedAt = &s
	}

	// 只有明确要求时才解密并返回密钥
	if includeSecret {
		signKey, err := r.encryptor.Decrypt(item.SignKey)
		if err != nil {
			return ConfigDTO{}, ErrDecryptionFailed
		}
		notifyKey, err := r.encryptor.Decrypt(item.NotifyKey)
		if err != nil {
			return ConfigDTO{}, ErrDecryptionFailed
		}
		dto.SignKey = signKey
		dto.NotifyKey = notifyKey
	}

	return dto, nil
}

// validateCreateRequest 验证创建请求

func firstNonEmpty(vals ...string) string {
	for _, v := range vals {
		if v != "" {
			return v
		}
	}
	return ""
}

func defaultSignType(provider string) string {
	if provider == "lakala" {
		return "SHA256withRSA"
	}
	return "MD5"
}
