package admin

import (
	"context"
	"strconv"

	"apps/backend/internal/module/member/domain"
	"apps/backend/internal/svc"
	"apps/backend/internal/types"

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

type SetEmailVerifiedLogic struct {
	logx.Logger
	ctx    context.Context
	svcCtx *svc.ServiceContext
}

func NewSetEmailVerifiedLogic(ctx context.Context, svcCtx *svc.ServiceContext) *SetEmailVerifiedLogic {
	return &SetEmailVerifiedLogic{Logger: logx.WithContext(ctx), ctx: ctx, svcCtx: svcCtx}
}

func (l *SetEmailVerifiedLogic) SetEmailVerified(req *types.AdminEmailVerifiedReq) (resp *types.MemberPublic, err error) {
	uid, err := strconv.ParseInt(req.Uid, 10, 64)
	if err != nil {
		return nil, err
	}
	m, err := l.svcCtx.Members.FindByUID(l.ctx, uid)
	if err != nil {
		return nil, err
	}
	m.EmailVerified = req.Verified
	if req.Verified {
		now := domain.NowNano()
		m.EmailVerifiedAt = &now
		if m.Status == domain.StatusUnverified {
			m.Status = domain.StatusActive
		}
	} else {
		m.EmailVerifiedAt = nil
	}
	m.UpdatedAt = domain.NowNano()
	if err := l.svcCtx.Members.UpdateMember(l.ctx, m); err != nil {
		return nil, err
	}
	return types.MemberFromModel(m), nil
}
