package admin_api

import (
	"context"

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

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

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

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

func (l *AdminGetApiListLogic) AdminGetApiList(req *types.AdminGetApiListReq) (resp *types.AdminGetApiListResp, err error) {
	// 1. 参数验证
	if req.Page <= 0 {
		req.Page = 1
	}
	if req.PageSize <= 0 {
		req.PageSize = 20
	}
	if req.PageSize > 100 {
		req.PageSize = 100
	}

	// 2. 构建查询条件
	builder := l.svcCtx.AdminApiModel.SelectBuilder()
	
	// 添加搜索条件
	if req.ApiName != "" {
		builder = builder.Where("api_name LIKE ?", "%"+req.ApiName+"%")
	}
	if req.Method != "" {
		builder = builder.Where("method = ?", req.Method)
	}
	if req.Status > 0 {
		builder = builder.Where("status = ?", req.Status)
	}

	// 3. 查询总数
	total, err := l.svcCtx.AdminApiModel.FindCount(l.ctx, builder, "id")
	if err != nil {
		return nil, errors.Wrapf(xerr.NewErrCode(xerr.DB_ERROR),
			"查询API总数失败, err: %v", err)
	}

	// 4. 查询列表
	apis, err := l.svcCtx.AdminApiModel.FindPageListByPage(l.ctx, builder, req.Page, req.PageSize, "id DESC")
	if err != nil {
		return nil, errors.Wrapf(xerr.NewErrCode(xerr.DB_ERROR),
			"查询API列表失败, err: %v", err)
	}

	// 5. 转换数据格式
	var apiList []types.AdminApiInfo
	for _, api := range apis {
		apiList = append(apiList, types.AdminApiInfo{
			Id:          api.Id,
			ApiName:     api.ApiName,
			ApiCode:     api.ApiCode,
			Method:      api.Method,
			Url:         api.Url,
			Status:      api.Status,
			Description: api.Description,
			CreateTime:  api.CreateTime.Format("2006-01-02 15:04:05"),
			UpdateTime:  api.UpdateTime.Format("2006-01-02 15:04:05"),
		})
	}

	// 6. 返回结果
	return &types.AdminGetApiListResp{
		Items: apiList,
		Total: total,
	}, nil
}
