package financewithdrawal

import (
	"context"
	"fmt"
	"strings"
	"time"

	"hyapp/pkg/dingtalkrobot"
)

type dingTalkNotifier struct {
	client *dingtalkrobot.Client
}

// NewDingTalkNotifier 创建用户提现申请通知器；nil client 表示当前环境不启用提醒。
func NewDingTalkNotifier(client *dingtalkrobot.Client) Notifier {
	if client == nil {
		return nil
	}
	return &dingTalkNotifier{client: client}
}

func (n *dingTalkNotifier) NotifyApplicationCreated(ctx context.Context, application Application) error {
	if n == nil || n.client == nil {
		return nil
	}
	return n.client.SendMarkdown(ctx, dingtalkrobot.MarkdownMessage{
		Title: "用户提现运营审核待处理【运营审核阶段】",
		Text:  withdrawalApplicationCreatedMarkdown(application),
	})
}

func withdrawalApplicationCreatedMarkdown(application Application) string {
	return strings.Join([]string{
		"### 用户提现运营审核待处理【运营审核阶段】",
		"",
		"- 当前阶段：**运营审核阶段**",
		fmt.Sprintf("- 申请ID：%d", application.ID),
		fmt.Sprintf("- APP：%s", markdownValue(application.AppCode)),
		fmt.Sprintf("- 用户ID：%d", application.UserID),
		fmt.Sprintf("- 工资资产：%s", markdownValue(application.SalaryAssetType)),
		fmt.Sprintf("- 提现金额：$ %s", markdownValue(application.WithdrawAmount)),
		fmt.Sprintf("- 提现方式：%s", markdownValue(application.WithdrawMethod)),
		fmt.Sprintf("- 提现地址：%s", markdownValue(application.WithdrawAddress)),
		fmt.Sprintf("- 冻结交易：%s", markdownValue(application.FreezeTransactionID)),
		fmt.Sprintf("- 申请时间：%s", markdownValue(formatNotifyMillis(application.CreatedAtMS))),
		"- 后台地址：https://admin-acc.global-interaction.com/finance/?view=withdrawalOperations",
	}, "\n")
}

func formatNotifyMillis(value int64) string {
	if value <= 0 {
		return "-"
	}
	// 财务人员按北京时间处理审核；数据库和接口仍保留 Unix 毫秒作为事实时间。
	return time.UnixMilli(value).In(time.FixedZone("UTC+8", 8*60*60)).Format("2006-01-02 15:04:05")
}

func markdownValue(value string) string {
	value = strings.TrimSpace(value)
	if value == "" {
		return "-"
	}
	if len([]rune(value)) > 240 {
		runes := []rune(value)
		value = string(runes[:240]) + "..."
	}
	replacer := strings.NewReplacer("\r", " ", "\n", " ", "\t", " ")
	return replacer.Replace(value)
}
