package admin_user

import (
	"context"

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

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

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

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

func (l *AdminDeleteUserLogic) AdminDeleteUser(req *types.AdminDeleteUserReq) (resp *types.AdminDeleteUserResp, err error) {
	// 检查用户是否存在
	_, err = l.svcCtx.AdminUserModel.FindOne(l.ctx, req.Id)
	if err != nil {
		return nil, errors.Wrapf(xerr.NewErrCode(xerr.DB_ERROR), "用户不存在: %v", err)
	}

	// 使用事务删除用户和关联数据
	err = l.svcCtx.AdminUserModel.Trans(l.ctx, func(ctx context.Context, session sqlx.Session) error {
		// 删除用户角色关联
		builder := l.svcCtx.AdminUserRoleModel.SelectBuilder().
			Where("user_id = ?", req.Id)
		roles, err := l.svcCtx.AdminUserRoleModel.FindAll(ctx, builder, "id ASC")
		if err != nil {
			return err
		}
		for _, role := range roles {
			err = l.svcCtx.AdminUserRoleModel.Delete(ctx, session, role.Id)
			if err != nil {
				return err
			}
		}

		// 删除用户
		err = l.svcCtx.AdminUserModel.Delete(ctx, session, req.Id)
		if err != nil {
			return err
		}

		return nil
	})

	if err != nil {
		return nil, errors.Wrapf(xerr.NewErrCode(xerr.DB_ERROR), "删除用户失败: %v", err)
	}

	return &types.AdminDeleteUserResp{
		Success: true,
	}, nil
}
