package admin_query

import (
	"context"
	"time"

	"tyc-server/app/main/api/internal/svc"
	"tyc-server/app/main/api/internal/types"
	"tyc-server/app/main/model"
	"tyc-server/common/xerr"

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

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

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

func (l *AdminUpdateQueryCleanupConfigLogic) AdminUpdateQueryCleanupConfig(req *types.AdminUpdateQueryCleanupConfigReq) (resp *types.AdminUpdateQueryCleanupConfigResp, err error) {
	// 使用事务处理更新操作
	err = l.svcCtx.QueryCleanupConfigModel.Trans(l.ctx, func(ctx context.Context, session sqlx.Session) error {
		// 1. 查询配置是否存在
		config, err := l.svcCtx.QueryCleanupConfigModel.FindOne(ctx, req.Id)
		if err != nil {
			if err == model.ErrNotFound {
				return errors.Wrapf(xerr.NewErrCode(xerr.DB_ERROR), "配置不存在, id: %d", req.Id)
			}
			return errors.Wrapf(xerr.NewErrCode(xerr.DB_ERROR), "查询配置失败, id: %d, err: %v", req.Id, err)
		}

		// 2. 更新配置
		config.ConfigValue = req.ConfigValue
		config.Status = req.Status
		config.UpdateTime = time.Now()

		_, err = l.svcCtx.QueryCleanupConfigModel.Update(ctx, session, config)
		if err != nil {
			return errors.Wrapf(xerr.NewErrCode(xerr.DB_ERROR), "更新配置失败, id: %d, err: %v", req.Id, err)
		}

		return nil
	})

	if err != nil {
		return nil, err
	}

	return &types.AdminUpdateQueryCleanupConfigResp{
		Success: true,
	}, nil
}
