package user

import (
	"backend/internal/svc"
	"backend/internal/types"
	errs "backend/pkg/library/errors"
	mbr "backend/pkg/member/domain/member"
	member "backend/pkg/member/domain/usecase"
	tokeneEntity "backend/pkg/permission/domain/entity"
	"backend/pkg/permission/domain/token"
	"context"

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

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

// NewUpdatePasswordLogic 修改當前登入使用者的密碼
func NewUpdatePasswordLogic(ctx context.Context, svcCtx *svc.ServiceContext) *UpdatePasswordLogic {
	return &UpdatePasswordLogic{
		Logger: logx.WithContext(ctx),
		ctx:    ctx,
		svcCtx: svcCtx,
	}
}

func (l *UpdatePasswordLogic) UpdatePassword(req *types.UpdatePasswordReq) (*types.RespOK, error) {
	if req.NewPassword != req.NewPasswordConfirm {
		return nil, errs.InputInvalidFormatError("failed to check token")
	}
	loginID := token.LoginID(l.ctx)
	// 驗證是否本地平台
	info, err := l.svcCtx.AccountUC.GetUserAccountInfo(l.ctx, member.GetUIDByAccountRequest{
		Account: loginID,
	})
	if err != nil {
		return nil, err
	}

	if info.Data.Platform != mbr.Digimon {
		return nil, errs.InputInvalidFormatError("failed th change password via third party login")
	}

	// 驗證舊密碼是否正確
	if _, err := l.svcCtx.AccountUC.VerifyPlatformAuthResult(l.ctx, member.VerifyAuthResultRequest{
		Account: loginID,
		Token:   req.CurrentPassword,
	}); err != nil {
		return nil, errs.AuthForbiddenError("failed to verify correct password")
	}

	// 更新
	err = l.svcCtx.AccountUC.UpdateUserToken(l.ctx, member.UpdateTokenRequest{
		Account:  loginID,
		Token:    req.NewPassword,
		Platform: mbr.Digimon.ToInt64(),
	})

	_ = l.svcCtx.TokenUC.CancelToken(l.ctx, tokeneEntity.CancelTokenReq{
		Token: req.Authorization.Authorization,
	})

	return &types.RespOK{}, nil
}
