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 AdminUpdateApiLogic struct {
	logx.Logger
	ctx    context.Context
	svcCtx *svc.ServiceContext
}

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

func (l *AdminUpdateApiLogic) AdminUpdateApi(req *types.AdminUpdateApiReq) (resp *types.AdminUpdateApiResp, err error) {
	// 1. 参数验证
	if req.Id <= 0 {
		return nil, errors.Wrapf(xerr.NewErrCode(xerr.PARAM_VERIFICATION_ERROR),
			"API ID必须大于0, id: %d", req.Id)
	}
	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是否存在
	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. 检查API编码是否被其他记录使用
	if api.ApiCode != req.ApiCode {
		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)
		}
	}

	// 4. 更新API信息
	api.ApiName = req.ApiName
	api.ApiCode = req.ApiCode
	api.Method = req.Method
	api.Url = req.Url
	api.Status = req.Status
	api.Description = req.Description

	_, err = l.svcCtx.AdminApiModel.Update(l.ctx, nil, api)
	if err != nil {
		return nil, errors.Wrapf(xerr.NewErrCode(xerr.DB_ERROR),
			"更新API失败, err: %v, id: %d", err, req.Id)
	}

	// 5. 返回结果
	return &types.AdminUpdateApiResp{Success: true}, nil
}
