package logic

import (
	"context"
	"encoding/json"
	"fmt"
	"juwan-backend/app/email/mq/internal/config"
	"juwan-backend/app/email/mq/internal/mailer"
	"juwan-backend/app/email/mq/internal/svc"
	"strings"

	"github.com/zeromicro/go-zero/core/logx"
)

type SendVerificationCodeMq struct {
	c      config.Config
	ctx    context.Context
	svcCxt *svc.ServiceContext
}

func NewSendVerificationCodeMq(ctx context.Context, c config.Config, svcCtx *svc.ServiceContext) *SendVerificationCodeMq {
	return &SendVerificationCodeMq{
		c:      c,
		ctx:    ctx,
		svcCxt: svcCtx,
	}
}

func (l *SendVerificationCodeMq) Consume(ctx context.Context, key, value string) error {
	logx.Infof("Consume get message key: %s, value: %s", key, value)
	if l.svcCxt.MailSender == nil {
		return fmt.Errorf("mail sender not initialized")
	}

	var payload verificationCodePayload
	if err := json.Unmarshal([]byte(value), &payload); err != nil {
		logx.Errorf("failed to unmarshal verification code payload: %v", err)
		return err
	}

	if payload.Type != "verification_code" {
		logx.Infof("skip unsupported email task type: %s", payload.Type)
		return nil
	}

	emailAddr := strings.TrimSpace(payload.Email)
	code := strings.TrimSpace(payload.Code)
	scene := strings.TrimSpace(payload.Scene)
	if emailAddr == "" || code == "" {
		logx.Errorf("invalid verification payload: email=%s, code=%s", emailAddr, code)
		return fmt.Errorf("invalid verification payload: email/code is required")
	}

	expireIn := payload.ExpireIn
	if expireIn <= 0 {
		expireIn = 60
	}

	subject := "Your verification code"
	body := fmt.Sprintf("你的验证码是 %s. 该验证码有效时间 %d 秒. 用途: %s. 单号: %s", code, expireIn, scene, payload.RequestID)
	// logx.Info("Send email to address: %s, subject: %s", emailAddr, subject)

	err := l.svcCxt.MailSender.Send(ctx, mailer.Message{
		To:      []string{emailAddr},
		Subject: subject,
		Body:    body,
		IsHTML:  false,
	})
	if err != nil {
		logx.Errorf("failed to send verification email to %s: %v", emailAddr, err)
		return err
	}

	logx.Infof("verification email sent to %s successfully", emailAddr)
	return nil
}

type verificationCodePayload struct {
	Type      string `json:"type"`
	RequestID string `json:"requestId"`
	Email     string `json:"email"`
	Scene     string `json:"scene"`
	Code      string `json:"code"`
	ExpireIn  int64  `json:"expireIn"`
}
