package admin_feature

import (
	"context"
	"encoding/hex"

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

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

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

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

func (l *AdminConfigFeatureExampleLogic) AdminConfigFeatureExample(req *types.AdminConfigFeatureExampleReq) (resp *types.AdminConfigFeatureExampleResp, err error) {
	// 1. 验证功能是否存在
	feature, err := l.svcCtx.FeatureModel.FindOne(l.ctx, req.FeatureId)
	if err != nil && !errors.Is(err, model.ErrNotFound) {
		return nil, errors.Wrapf(xerr.NewErrCode(xerr.DB_ERROR),
			"查询功能失败, featureId: %d, err: %v", req.FeatureId, err)
	}
	if feature == nil {
		return nil, errors.Wrapf(xerr.NewErrCode(xerr.REUQEST_PARAM_ERROR),
			"功能不存在, featureId: %d", req.FeatureId)
	}

	// 2. 检查是否已存在示例数据
	existingExample, err := l.svcCtx.ExampleModel.FindOneByFeatureId(l.ctx, req.FeatureId)
	if err != nil && !errors.Is(err, model.ErrNotFound) {
		return nil, errors.Wrapf(xerr.NewErrCode(xerr.DB_ERROR),
			"查询示例数据失败, featureId: %d, err: %v", req.FeatureId, err)
	}

	// 3. 加密示例数据
	secretKey := l.svcCtx.Config.Encrypt.SecretKey
	key, decodeErr := hex.DecodeString(secretKey)
	if decodeErr != nil {
		return nil, errors.Wrapf(xerr.NewErrCode(xerr.SERVER_COMMON_ERROR),
			"获取AES密钥失败: %v", decodeErr)
	}

	encryptedData, aesEncryptErr := crypto.AesEncrypt([]byte(req.Data), key)
	if aesEncryptErr != nil {
		return nil, errors.Wrapf(xerr.NewErrCode(xerr.SERVER_COMMON_ERROR),
			"加密示例数据失败: %v", aesEncryptErr)
	}

	// 4. 准备示例数据
	exampleData := &model.Example{
		ApiId:     feature.ApiId,
		FeatureId: req.FeatureId,
		Content:   encryptedData,
	}

	// 4. 根据是否存在决定新增或更新
	if existingExample == nil {
		// 新增示例数据
		_, err = l.svcCtx.ExampleModel.Insert(l.ctx, nil, exampleData)
		if err != nil {
			return nil, errors.Wrapf(xerr.NewErrCode(xerr.DB_ERROR),
				"创建示例数据失败, featureId: %d, err: %v", req.FeatureId, err)
		}
	} else {
		// 更新示例数据
		exampleData.Id = existingExample.Id
		exampleData.Version = existingExample.Version
		_, err = l.svcCtx.ExampleModel.Update(l.ctx, nil, exampleData)
		if err != nil {
			return nil, errors.Wrapf(xerr.NewErrCode(xerr.DB_ERROR),
				"更新示例数据失败, featureId: %d, err: %v", req.FeatureId, err)
		}
	}

	// 5. 返回成功结果
	return &types.AdminConfigFeatureExampleResp{Success: true}, nil
}
