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

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

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

	// 删除现有权限
	for _, roleApi := range roleApis {
		err = l.svcCtx.AdminRoleApiModel.DeleteSoft(l.ctx, nil, roleApi)
		if err != nil {
			logx.Errorf("删除角色API权限失败, err: %v, roleId: %d, apiId: %d", err, req.RoleId, roleApi.ApiId)
		}
	}

	// 4. 添加新的API权限
	if len(req.ApiIds) > 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
			}

			// 创建新的关联
			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)
			}
		}
	}

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