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

package verification_user

import (
	"context"
	"encoding/json"
	"errors"
	"juwan-backend/app/user_verifications/rpc/pb"
	"juwan-backend/app/users/api/internal/svc"
	"juwan-backend/app/users/api/internal/types"
	"juwan-backend/common/utils/contextj"

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

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

// 提交或修改角色认证申请 (支持幂等更新)
func NewApplyVerificationLogic(ctx context.Context, svcCtx *svc.ServiceContext) *ApplyVerificationLogic {
	return &ApplyVerificationLogic{
		Logger: logx.WithContext(ctx),
		ctx:    ctx,
		svcCtx: svcCtx,
	}
}

func (l *ApplyVerificationLogic) ApplyVerification(req *types.ApplyVerificationReq) (resp *types.VerificationEmptyResp, err error) {
	userId, err := contextj.UserIDFrom(l.ctx)
	if err != nil {
		logx.Errorf("get user id from context: %v", err)
		return nil, contextj.ERRILLEGALUSER
	}

	materials, err := json.Marshal(req.Materials)
	if err != nil {
		logx.Errorf("marshal materials: %v", err)
		return nil, err
	}

	_, err = l.svcCtx.UserVerificationsRpc.AddOrUpdateUserVerifications(l.ctx, &pb.AddOrUpdateUserVerificationsReq{
		UserId:   userId,
		Role:     req.Role,
		Material: string(materials),
	})
	if err != nil {
		logx.Errorf("call AddOrUpdateUserVerifications: %v", err)
		return nil, errors.New("apply verification failed: " + err.Error())
	}

	return &types.VerificationEmptyResp{}, nil
}
