// Code scaffolded by goctl. Safe to edit.
// goctl 1.10.1

package member

import (
	"context"
	"strings"

	domusecase "gateway/internal/model/member/domain/usecase"
	"gateway/internal/svc"
	"gateway/internal/types"

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

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

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

func (l *ChangePasswordLogic) ChangePassword(req *types.ChangePasswordReq) (*types.ChangePasswordData, error) {
	actor, err := actorOrErr(l.ctx)
	if err != nil {
		return nil, err
	}
	if l.svcCtx.MemberProfile == nil {
		return nil, errb.SysNotImplemented("member profile not configured")
	}
	if l.svcCtx.Zitadel == nil {
		return nil, errb.SysNotImplemented("zitadel not configured")
	}
	if req == nil {
		return nil, errb.InputMissingRequired("request body is required")
	}

	member, err := l.svcCtx.MemberProfile.GetByUID(l.ctx, &domusecase.GetMemberRequest{
		TenantID: actor.TenantID,
		UID:      actor.UID,
	})
	if err != nil {
		return nil, err
	}
	if err := ensurePlatformNativePassword(member); err != nil {
		return nil, err
	}
	if err := ensurePasswordChangeStepUp(l.ctx, l.svcCtx, actor.TenantID, actor.UID, member, req); err != nil {
		return nil, err
	}
	if member.ZitadelUserID == "" {
		return nil, errb.ResInvalidState("member has no zitadel identity")
	}

	email := strings.TrimSpace(member.ZitadelEmail)
	if email == "" {
		return nil, errb.ResInvalidState("member has no login email")
	}
	if _, err := l.svcCtx.Zitadel.VerifyPassword(l.ctx, email, req.CurrentPassword); err != nil {
		return nil, errb.AuthUnauthorized("invalid current password")
	}
	if err := l.svcCtx.Zitadel.SetUserPassword(l.ctx, member.ZitadelUserID, req.NewPassword, req.CurrentPassword); err != nil {
		return nil, errb.SvcThirdParty("zitadel password update failed").WithCause(err)
	}

	return &types.ChangePasswordData{OK: true}, nil
}
