package query

import (
	"context"
	"database/sql"
	"encoding/hex"

	"qnc-server/app/main/api/internal/svc"
	"qnc-server/app/main/api/internal/types"
	"qnc-server/app/main/model"
	"qnc-server/common/xerr"
	"qnc-server/pkg/lzkit/crypto"

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

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

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

func (l *QueryRecheckLogic) QueryRecheck(req *types.QueryRecheckReq) (resp *types.QueryRecheckResp, err error) {
	query, err := l.svcCtx.QueryModel.FindOne(l.ctx, req.QueryId)
	if err != nil {
		return nil, errors.Wrapf(xerr.NewErrCode(xerr.DB_ERROR), "补查, 获取query失败, %v", err)
	}
	secretKey := l.svcCtx.Config.Encrypt.SecretKey
	key, decodeErr := hex.DecodeString(secretKey)
	if decodeErr != nil {
		return nil, errors.Wrapf(xerr.NewErrCode(xerr.SERVER_COMMON_ERROR), "补查, 获取密钥失败, %v", err)
	}
	decryptData, aesdecryptErr := crypto.AesDecrypt(query.QueryParams, key)
	if aesdecryptErr != nil {
		return nil, errors.Wrapf(xerr.NewErrCode(xerr.SERVER_COMMON_ERROR), "补查, 解密参数失败: %+v", aesdecryptErr)
	}
	combinedResponse, err := l.svcCtx.ApiRequestService.ProcessRequests(decryptData, query.ProductId)
	if err != nil {
		return nil, errors.Wrapf(xerr.NewErrCode(xerr.SERVER_COMMON_ERROR), "补查, 处理请求失败: %v", err)
	}
	encryptData, aesEncryptErr := crypto.AesEncrypt(combinedResponse, key)
	if aesEncryptErr != nil {
		return nil, errors.Wrapf(xerr.NewErrCode(xerr.SERVER_COMMON_ERROR), "补查, 加密响应信息失败: %v", aesEncryptErr)
	}
	query.QueryData = sql.NullString{
		String: encryptData,
		Valid:  true,
	}
	query.QueryState = model.QueryStateSuccess
	updateErr := l.svcCtx.QueryModel.UpdateWithVersion(l.ctx, nil, query)
	if updateErr != nil {
		return nil, errors.Wrapf(xerr.NewErrCode(xerr.DB_ERROR), "补查, 保存响应数据失败: %v", updateErr)
	}
	return &types.QueryRecheckResp{
		Success: true,
	}, nil
}
