package admin_feature

import (
	"context"
	"encoding/hex"

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

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

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

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

func (l *AdminGetFeatureExampleLogic) AdminGetFeatureExample(req *types.AdminGetFeatureExampleReq) (resp *types.AdminGetFeatureExampleResp, err error) {
	// 1. 查询示例数据
	example, err := l.svcCtx.ExampleModel.FindOneByFeatureId(l.ctx, req.FeatureId)
	if err != nil {
		if errors.Is(err, model.ErrNotFound) {
			// 示例数据不存在，返回空数据
			return &types.AdminGetFeatureExampleResp{
				Id:         "",
				FeatureId:  req.FeatureId,
				ApiId:      "",
				Data:       "",
				CreateTime: "",
				UpdateTime: "",
			}, nil
		}
		return nil, errors.Wrapf(xerr.NewErrCode(xerr.DB_ERROR),
			"查询示例数据失败, featureId: %d, err: %v", req.FeatureId, err)
	}

	// 2. 获取解密密钥
	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)
	}

	// 3. 解密示例数据
	var decryptedData string
	if example.Content == "000" {
		// 特殊值，直接返回
		decryptedData = example.Content
	} else {
		// 解密数据
		decryptedBytes, decryptErr := crypto.AesDecrypt(example.Content, key)
		if decryptErr != nil {
			return nil, errors.Wrapf(xerr.NewErrCode(xerr.SERVER_COMMON_ERROR),
				"解密示例数据失败: %v", decryptErr)
		}
		decryptedData = string(decryptedBytes)
	}

	// 4. 返回解密后的数据
	return &types.AdminGetFeatureExampleResp{
		Id:         example.Id,
		FeatureId:  example.FeatureId,
		ApiId:      example.ApiId,
		Data:       decryptedData,
		CreateTime: example.CreateTime.Format("2006-01-02 15:04:05"),
		UpdateTime: example.UpdateTime.Format("2006-01-02 15:04:05"),
	}, nil
}
