package admin_role_api

import (
	"context"

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

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

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

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

func (l *AdminGetRoleApiListLogic) AdminGetRoleApiList(req *types.AdminGetRoleApiListReq) (resp *types.AdminGetRoleApiListResp, err error) {
	// 1. 参数验证
	if req.RoleId == "" {
		return nil, errors.Wrapf(xerr.NewErrCode(xerr.PARAM_VERIFICATION_ERROR),
			"角色ID不能为空, roleId: %s", req.RoleId)
	}

	// 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: %s", req.RoleId)
		}
		return nil, errors.Wrapf(xerr.NewErrCode(xerr.DB_ERROR),
			"查询角色失败, err: %v, roleId: %d", err, req.RoleId)
	}

	// 3. 查询角色API权限列表
	builder := l.svcCtx.AdminRoleApiModel.SelectBuilder().
		Where("role_id = ?", req.RoleId)

	roleApis, err := l.svcCtx.AdminRoleApiModel.FindAll(l.ctx, builder, "")
	if err != nil {
		return nil, errors.Wrapf(xerr.NewErrCode(xerr.DB_ERROR),
			"查询角色API权限失败, err: %v, roleId: %d", err, req.RoleId)
	}

	// 4. 转换数据格式
	var apiList []types.AdminRoleApiInfo
	for _, roleApi := range roleApis {
		// 查询API详情
		api, err := l.svcCtx.AdminApiModel.FindOne(l.ctx, roleApi.ApiId)
		if err != nil {
			logx.Errorf("查询API详情失败, err: %v, apiId: %d", err, roleApi.ApiId)
			continue
		}

		apiList = append(apiList, types.AdminRoleApiInfo{
			Id:          roleApi.Id,
			RoleId:      roleApi.RoleId,
			ApiId:       roleApi.ApiId,
			ApiName:     api.ApiName,
			ApiCode:     api.ApiCode,
			Method:      api.Method,
			Url:         api.Url,
			Status:      api.Status,
			Description: api.Description,
		})
	}

	// 5. 返回结果
	return &types.AdminGetRoleApiListResp{
		Items: apiList,
	}, nil
}
