package user

import (
	"context"
	"in-server/common/ctxdata"
	"in-server/common/xerr"

	"github.com/zeromicro/go-zero/core/mr"

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

	"in-server/app/main/api/internal/svc"

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

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

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

func (l *CancelOutLogic) CancelOut() error {
	userID, getUserIdErr := ctxdata.GetUidFromCtx(l.ctx)
	if getUserIdErr != nil {
		return errors.Wrapf(xerr.NewErrCode(xerr.SERVER_COMMON_ERROR), "用户信息, %v", getUserIdErr)
	}

	// 在事务中处理用户注销相关操作
	err := l.svcCtx.UserModel.Trans(l.ctx, func(tranCtx context.Context, session sqlx.Session) error {
		// 1. 删除用户基本信息
		if err := l.svcCtx.UserModel.Delete(tranCtx, session, userID); err != nil {
			return errors.Wrapf(err, "删除用户基本信息失败, userId: %d", userID)
		}

		// 2. 查询并删除用户授权信息
		UserAuthModelBuilder := l.svcCtx.UserAuthModel.SelectBuilder().Where("user_id = ?", userID)
		userAuths, err := l.svcCtx.UserAuthModel.FindAll(tranCtx, UserAuthModelBuilder, "")
		if err != nil && !errors.Is(err, sqlx.ErrNotFound) {
			return errors.Wrapf(err, "查询用户授权信息失败, userId: %d", userID)
		}

		// 并发删除用户授权信息
		if len(userAuths) > 0 {
			funcs := make([]func() error, len(userAuths))
			for i, userAuth := range userAuths {
				authID := userAuth.Id
				funcs[i] = func() error {
					return l.svcCtx.UserAuthModel.Delete(tranCtx, session, authID)
				}
			}

			if err := mr.Finish(funcs...); err != nil {
				return errors.Wrapf(err, "删除用户授权信息失败")
			}
		}

		// 5. 删除用户查询记录
		queryBuilder := l.svcCtx.QueryModel.SelectBuilder().Where("user_id = ?", userID)
		queries, err := l.svcCtx.QueryModel.FindAll(tranCtx, queryBuilder, "")
		if err != nil && !errors.Is(err, sqlx.ErrNotFound) {
			return errors.Wrapf(err, "查询用户查询记录失败, userId: %d", userID)
		}

		if len(queries) > 0 {
			queryFuncs := make([]func() error, len(queries))
			for i, query := range queries {
				queryId := query.Id
				queryFuncs[i] = func() error {
					return l.svcCtx.QueryModel.Delete(tranCtx, session, queryId)
				}
			}

			if err := mr.Finish(queryFuncs...); err != nil {
				return errors.Wrapf(err, "删除用户查询记录失败")
			}
		}

		// 6. 删除用户订单记录
		orderBuilder := l.svcCtx.OrderModel.SelectBuilder().Where("user_id = ?", userID)
		orders, err := l.svcCtx.OrderModel.FindAll(tranCtx, orderBuilder, "")
		if err != nil && !errors.Is(err, sqlx.ErrNotFound) {
			return errors.Wrapf(err, "查询用户订单记录失败, userId: %d", userID)
		}

		if len(orders) > 0 {
			orderFuncs := make([]func() error, len(orders))
			for i, order := range orders {
				orderId := order.Id
				orderFuncs[i] = func() error {
					return l.svcCtx.OrderModel.Delete(tranCtx, session, orderId)
				}
			}

			if err := mr.Finish(orderFuncs...); err != nil {
				return errors.Wrapf(err, "删除用户订单记录失败")
			}
		}

		return nil
	})

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

	return nil
}
