package logic

import (
	"context"
	"encoding/json"
	"errors"
	"juwan-backend/app/snowflake/rpc/snowflake"
	"juwan-backend/app/user_verifications/rpc/internal/models/schema"

	"juwan-backend/app/user_verifications/rpc/internal/svc"
	"juwan-backend/app/user_verifications/rpc/pb"

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

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

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

// -----------------------userVerifications-----------------------
func (l *AddUserVerificationsLogic) AddUserVerifications(in *pb.AddUserVerificationsReq) (*pb.AddUserVerificationsResp, error) {
	nextIdResp, err := l.svcCtx.SnowflakeRpc.NextId(l.ctx, &snowflake.NextIdReq{})
	if err != nil {
		return nil, err
	}

	materials := schema.MaterialStruct{}
	err = json.Unmarshal([]byte(in.Materials), &materials)
	if err != nil {
		logx.Errorf("Unmarshal %v materials failed: %s", in.Materials, err)
		return nil, errors.New("bad input materials")
	}

	err = l.svcCtx.UserVeriModelRW.Create().
		SetID(nextIdResp.Id).
		SetUserID(in.UserId).
		SetRole(in.Role).
		SetStatus("padding").
		SetMaterials(materials).
		Exec(l.ctx)
	if err != nil {
		return nil, err
	}

	return &pb.AddUserVerificationsResp{}, nil
}
