package admin_role_api

import (
	"context"

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

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

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

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

func (l *AdminGetAllApiListLogic) AdminGetAllApiList(req *types.AdminGetAllApiListReq) (resp *types.AdminGetAllApiListResp, err error) {
	// 1. 构建查询条件
	builder := l.svcCtx.AdminApiModel.SelectBuilder()

	// 添加状态过滤
	if req.Status > 0 {
		builder = builder.Where("status = ?", req.Status)
	}

	// 2. 查询所有API列表
	apis, err := l.svcCtx.AdminApiModel.FindAll(l.ctx, builder, "id ASC")
	if err != nil {
		return nil, errors.Wrapf(xerr.NewErrCode(xerr.DB_ERROR),
			"查询API列表失败, err: %v", err)
	}

	// 3. 转换数据格式
	var apiList []types.AdminRoleApiInfo
	for _, api := range apis {
		apiList = append(apiList, types.AdminRoleApiInfo{
			Id:          api.Id,
			RoleId:      "",
			ApiId:       api.Id,
			ApiName:     api.ApiName,
			ApiCode:     api.ApiCode,
			Method:      api.Method,
			Url:         api.Url,
			Status:      api.Status,
			Description: api.Description,
		})
	}

	// 4. 返回结果
	return &types.AdminGetAllApiListResp{
		Items: apiList,
	}, nil
}
