package admin_api

import (
	"context"

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

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

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

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

func (l *AdminCreateApiLogic) AdminCreateApi(req *types.AdminCreateApiReq) (resp *types.AdminCreateApiResp, err error) {
	// 1. 参数验证
	if req.ApiName == "" {
		return nil, errors.Wrapf(xerr.NewErrCode(xerr.PARAM_VERIFICATION_ERROR),
			"API名称不能为空")
	}
	if req.ApiCode == "" {
		return nil, errors.Wrapf(xerr.NewErrCode(xerr.PARAM_VERIFICATION_ERROR),
			"API编码不能为空")
	}
	if req.Method == "" {
		return nil, errors.Wrapf(xerr.NewErrCode(xerr.PARAM_VERIFICATION_ERROR),
			"请求方法不能为空")
	}
	if req.Url == "" {
		return nil, errors.Wrapf(xerr.NewErrCode(xerr.PARAM_VERIFICATION_ERROR),
			"API路径不能为空")
	}

	// 2. 检查API编码是否已存在
	existing, err := l.svcCtx.AdminApiModel.FindOneByApiCode(l.ctx, req.ApiCode)
	if err != nil && !errors.Is(err, model.ErrNotFound) {
		return nil, errors.Wrapf(xerr.NewErrCode(xerr.DB_ERROR),
			"查询API失败, err: %v, apiCode: %s", err, req.ApiCode)
	}
	if existing != nil {
		return nil, errors.Wrapf(xerr.NewErrCode(xerr.PARAM_VERIFICATION_ERROR),
			"API编码已存在: %s", req.ApiCode)
	}

	// 3. 创建API记录
	apiData := &model.AdminApi{
		ApiName:     req.ApiName,
		ApiCode:     req.ApiCode,
		Method:      req.Method,
		Url:         req.Url,
		Status:      req.Status,
		Description: req.Description,
	}

	result, err := l.svcCtx.AdminApiModel.Insert(l.ctx, nil, apiData)
	if err != nil {
		return nil, errors.Wrapf(xerr.NewErrCode(xerr.DB_ERROR),
			"创建API失败, err: %v", err)
	}

	// 4. 返回结果
	apiId, _ := result.LastInsertId()
	return &types.AdminCreateApiResp{Id: apiId}, nil
}
