package admin_api

import (
	"context"

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

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

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

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

func (l *AdminDeleteApiLogic) AdminDeleteApi(req *types.AdminDeleteApiReq) (resp *types.AdminDeleteApiResp, 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. 检查是否有角色关联该API
	roleApiBuilder := l.svcCtx.AdminRoleApiModel.SelectBuilder().Where("api_id = ?", req.Id)
	roleApis, err := l.svcCtx.AdminRoleApiModel.FindAll(l.ctx, roleApiBuilder, "")
	if err != nil {
		return nil, errors.Wrapf(xerr.NewErrCode(xerr.DB_ERROR),
			"查询角色API关联失败, err: %v, apiId: %d", err, req.Id)
	}
	if len(roleApis) > 0 {
		return nil, errors.Wrapf(xerr.NewErrCode(xerr.PARAM_VERIFICATION_ERROR),
			"该API已被角色使用，无法删除, apiId: %d", req.Id)
	}

	// 4. 执行软删除
	err = l.svcCtx.AdminApiModel.DeleteSoft(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.AdminDeleteApiResp{Success: true}, nil
}
