package admin_feature

import (
	"context"

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

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

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

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

func (l *AdminGetFeatureListLogic) AdminGetFeatureList(req *types.AdminGetFeatureListReq) (resp *types.AdminGetFeatureListResp, err error) {
	// 1. 构建查询条件
	builder := l.svcCtx.FeatureModel.SelectBuilder()

	// 2. 添加查询条件
	if req.ApiId != nil && *req.ApiId != "" {
		builder = builder.Where("api_id LIKE ?", "%"+*req.ApiId+"%")
	}
	if req.Name != nil && *req.Name != "" {
		builder = builder.Where("name LIKE ?", "%"+*req.Name+"%")
	}

	// 3. 执行分页查询
	list, total, err := l.svcCtx.FeatureModel.FindPageListByPageWithTotal(
		l.ctx, builder, req.Page, req.PageSize, "id DESC")
	if err != nil {
		return nil, errors.Wrapf(xerr.NewErrCode(xerr.DB_ERROR),
			"查询功能列表失败, err: %v, req: %+v", err, req)
	}

	// 4. 构建响应列表
	items := make([]types.FeatureListItem, 0, len(list))
	for _, item := range list {
		listItem := types.FeatureListItem{
			Id:         item.Id,
			ApiId:      item.ApiId,
			Name:       item.Name,
			CreateTime: item.CreateTime.Format("2006-01-02 15:04:05"),
			UpdateTime: item.UpdateTime.Format("2006-01-02 15:04:05"),
		}
		items = append(items, listItem)
	}

	// 5. 返回结果
	return &types.AdminGetFeatureListResp{
		Total: total,
		Items: items,
	}, nil
}
