package admin_query

import (
	"context"
	"in-server/app/main/api/internal/svc"
	"in-server/app/main/api/internal/types"
	"in-server/common/globalkey"
	"in-server/common/xerr"

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

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

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

func (l *AdminGetQueryCleanupConfigListLogic) AdminGetQueryCleanupConfigList(req *types.AdminGetQueryCleanupConfigListReq) (resp *types.AdminGetQueryCleanupConfigListResp, err error) {
	// 构建查询条件
	builder := l.svcCtx.QueryCleanupConfigModel.SelectBuilder().
		Where("del_state = ?", globalkey.DelStateNo)

	if req.Status > 0 {
		builder = builder.Where("status = ?", req.Status)
	}

	// 查询配置列表
	configs, err := l.svcCtx.QueryCleanupConfigModel.FindAll(l.ctx, builder, "id ASC")
	if err != nil {
		return nil, errors.Wrapf(xerr.NewErrCode(xerr.DB_ERROR), "查询清理配置列表失败 err: %v", err)
	}

	// 构建响应
	resp = &types.AdminGetQueryCleanupConfigListResp{
		Items: make([]types.QueryCleanupConfigItem, 0, len(configs)),
	}

	for _, config := range configs {
		item := types.QueryCleanupConfigItem{
			Id:          config.Id,
			ConfigKey:   config.ConfigKey,
			ConfigValue: config.ConfigValue,
			ConfigDesc:  config.ConfigDesc,
			Status:      config.Status,
			CreateTime:  config.CreateTime.Format("2006-01-02 15:04:05"),
			UpdateTime:  config.UpdateTime.Format("2006-01-02 15:04:05"),
		}
		resp.Items = append(resp.Items, item)
	}

	return resp, nil
}
