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

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

func (l *AdminAssignRoleApiLogic) AdminAssignRoleApi(req *types.AdminAssignRoleApiReq) (resp *types.AdminAssignRoleApiResp, err error) {
	// 1. 参数验证
	if req.RoleId <= 0 {
		return nil, errors.Wrapf(xerr.NewErrCode(xerr.PARAM_VERIFICATION_ERROR),
			"角色ID必须大于0, roleId: %d", 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 <= 0 {
			continue
		}

		// 检查API是否存在
		_, err := l.svcCtx.AdminApiModel.FindOne(l.ctx, apiId)
		if err != nil {
			if errors.Is(err, model.ErrNotFound) {
				logx.Errorf("API不存在, apiId: %d", apiId)
				continue
			}
			logx.Errorf("查询API失败, err: %v, apiId: %d", err, apiId)
			continue
		}

		// 检查是否已存在关联
		existing, err := l.svcCtx.AdminRoleApiModel.FindOneByRoleIdApiId(l.ctx, req.RoleId, apiId)
		if err != nil && !errors.Is(err, model.ErrNotFound) {
			logx.Errorf("查询角色API关联失败, err: %v, roleId: %d, apiId: %d", err, req.RoleId, apiId)
			continue
		}
		if existing != nil {
			continue // 已存在，跳过
		}

		// 创建关联
		roleApiData := &model.AdminRoleApi{
			RoleId: req.RoleId,
			ApiId:  apiId,
		}

		_, err = l.svcCtx.AdminRoleApiModel.Insert(l.ctx, nil, roleApiData)
		if err != nil {
			logx.Errorf("创建角色API关联失败, err: %v, roleId: %d, apiId: %d", err, req.RoleId, apiId)
			continue
		}

		successCount++
	}

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