package admin_api

import (
	"context"

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

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

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

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

func (l *AdminGetApiDetailLogic) AdminGetApiDetail(req *types.AdminGetApiDetailReq) (resp *types.AdminGetApiDetailResp, err error) {
	// 1. 参数验证
	if req.Id == "" {
		return nil, errors.Wrapf(xerr.NewErrCode(xerr.PARAM_VERIFICATION_ERROR),
			"API ID不能为空, id: %s", req.Id)
	}

	// 2. 查询API详情
	api, err := l.svcCtx.AdminApiModel.FindOne(l.ctx, req.Id)
	if err != nil {
		if errors.Is(err, model.ErrNotFound) {
			return nil, errors.Wrapf(xerr.NewErrCode(xerr.DB_ERROR),
				"API不存在, id: %d", req.Id)
		}
		return nil, errors.Wrapf(xerr.NewErrCode(xerr.DB_ERROR),
			"查询API详情失败, err: %v, id: %d", err, req.Id)
	}

	// 3. 返回结果
	return &types.AdminGetApiDetailResp{
		AdminApiInfo: 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"),
		},
	}, nil
}
