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

package auth

import (
	"context"

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

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

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

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

func (l *PasswordResetLogic) PasswordReset(req *types.PasswordResetReq) (*types.PasswordResetData, error) {
	if err := requireRegistrationDeps(l.svcCtx); err != nil {
		return nil, err
	}
	if l.svcCtx.Zitadel == nil {
		return nil, errb.SysNotImplemented("zitadel not configured")
	}
	if req == nil {
		return nil, errb.InputMissingRequired("request body is required")
	}

	tenant, err := resolveTenant(l.ctx, l.svcCtx, req.TenantSlug)
	if err != nil {
		return nil, err
	}

	ch, err := l.svcCtx.MemberOTP.MatchChallenge(l.ctx, &dommember.MatchChallengeRequest{
		ChallengeID:   req.ChallengeID,
		TenantID:      tenant.TenantID,
		Purpose:       passwordResetPurpose(),
		RequireUID:    true,
		RequireTarget: true,
	})
	if err != nil {
		return nil, err
	}

	member, err := l.svcCtx.MemberProfile.GetByUID(l.ctx, &dommember.GetMemberRequest{
		TenantID: tenant.TenantID,
		UID:      ch.UID,
	})
	if err != nil {
		return nil, err
	}
	if err := ensurePlatformNativePassword(member); err != nil {
		return nil, err
	}
	if err := ensurePasswordResetEligible(member.Status); err != nil {
		return nil, err
	}
	if member.ZitadelUserID == "" {
		return nil, errb.ResInvalidState("member has no zitadel identity")
	}

	if _, err := l.svcCtx.MemberOTP.Verify(l.ctx, &dommember.VerifyOTPRequest{
		TenantID:    tenant.TenantID,
		UID:         ch.UID,
		ChallengeID: req.ChallengeID,
		Code:        req.Code,
		Purpose:     passwordResetPurpose(),
	}); err != nil {
		return nil, err
	}

	if err := l.svcCtx.Zitadel.SetUserPassword(l.ctx, member.ZitadelUserID, req.NewPassword, ""); err != nil {
		return nil, wrapZitadelErr(err)
	}

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