package admin_role_api

import (
	"context"

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

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

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

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

func (l *AdminRemoveRoleApiLogic) AdminRemoveRoleApi(req *types.AdminRemoveRoleApiReq) (resp *types.AdminRemoveRoleApiResp, err error) {
	// 1. 参数验证
	if req.RoleId == "" {
		return nil, errors.Wrapf(xerr.NewErrCode(xerr.PARAM_VERIFICATION_ERROR),
			"角色ID不能为空, roleId: %s", req.RoleId)
	}
	if len(req.ApiIds) == 0 {
		return nil, errors.Wrapf(xerr.NewErrCode(xerr.PARAM_VERIFICATION_ERROR),
			"API ID列表不能为空")
	}

	// 2. 查询角色是否存在
	_, err = l.svcCtx.AdminRoleModel.FindOne(l.ctx, req.RoleId)
	if err != nil {
		if errors.Is(err, model.ErrNotFound) {
			return nil, errors.Wrapf(xerr.NewErrCode(xerr.DB_ERROR),
				"角色不存在, roleId: %d", req.RoleId)
		}
		return nil, errors.Wrapf(xerr.NewErrCode(xerr.DB_ERROR),
			"查询角色失败, err: %v, roleId: %d", err, req.RoleId)
	}

	// 3. 批量移除API权限
	successCount := 0
	for _, apiId := range req.ApiIds {
		if apiId == "" {
			continue
		}

		// 查询关联记录
		roleApi, err := l.svcCtx.AdminRoleApiModel.FindOneByRoleIdApiId(l.ctx, req.RoleId, apiId)
		if err != nil {
			if errors.Is(err, model.ErrNotFound) {
				continue // 不存在，跳过
			}
			logx.Errorf("查询角色API关联失败, err: %v, roleId: %s, apiId: %s", err, req.RoleId, apiId)
			continue
		}

		// 删除关联
		err = l.svcCtx.AdminRoleApiModel.DeleteSoft(l.ctx, nil, roleApi)
		if err != nil {
			logx.Errorf("删除角色API关联失败, err: %v, roleId: %d, apiId: %d", err, req.RoleId, apiId)
			continue
		}

		successCount++
	}

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