package group

import (
	"context"

	"github.com/perfect-panel/server/internal/model/group"
	"github.com/perfect-panel/server/internal/model/node"
	"github.com/perfect-panel/server/internal/model/subscribe"
	"github.com/perfect-panel/server/internal/model/system"
	"github.com/perfect-panel/server/internal/model/user"
	"github.com/perfect-panel/server/internal/svc"
	"github.com/perfect-panel/server/pkg/logger"
	"gorm.io/gorm"
)

type ResetGroupsLogic struct {
	logger.Logger
	ctx    context.Context
	svcCtx *svc.ServiceContext
}

// NewResetGroupsLogic Reset all groups (delete all node groups and reset related data)
func NewResetGroupsLogic(ctx context.Context, svcCtx *svc.ServiceContext) *ResetGroupsLogic {
	return &ResetGroupsLogic{
		Logger: logger.WithContext(ctx),
		ctx:    ctx,
		svcCtx: svcCtx,
	}
}

func (l *ResetGroupsLogic) ResetGroups() error {
	err := l.svcCtx.DB.Transaction(func(tx *gorm.DB) error {
		// 1. Delete all node groups
		if err := tx.Where("1 = 1").Delete(&group.NodeGroup{}).Error; err != nil {
			l.Errorw("Failed to delete all node groups", logger.Field("error", err.Error()))
			return err
		}
		l.Infow("Successfully deleted all node groups")

		// 2. Clear node_group_id/node_group_ids for all subscribes (products)
		if err := tx.Table((&subscribe.Subscribe{}).TableName()).Where("1 = 1").Updates(map[string]interface{}{
			"node_group_id":  0,
			"node_group_ids": "[]",
		}).Error; err != nil {
			l.Errorw("Failed to clear subscribes' node groups", logger.Field("error", err.Error()))
			return err
		}
		l.Infow("Successfully cleared all subscribes' node groups")

		// 3. Clear node_group_ids for all nodes
		if err := tx.Table((&node.Node{}).TableName()).Where("1 = 1").Update("node_group_ids", "[]").Error; err != nil {
			l.Errorw("Failed to clear nodes' node_group_ids", logger.Field("error", err.Error()))
			return err
		}
		l.Infow("Successfully cleared all nodes' node_group_ids")

		// 4. Clear user_subscribe node_group_id
		if err := tx.Table((&user.Subscribe{}).TableName()).Where("1 = 1").Update("node_group_id", 0).Error; err != nil {
			l.Errorw("Failed to clear user subscribes' node_group_id", logger.Field("error", err.Error()))
			return err
		}
		l.Infow("Successfully cleared all user subscribes' node_group_id")

		// 5. Clear group history
		if err := tx.Where("1 = 1").Delete(&group.GroupHistory{}).Error; err != nil {
			l.Errorw("Failed to clear group history", logger.Field("error", err.Error()))
			return err
		}
		l.Infow("Successfully cleared group history")

		// 6. Clear group history details
		if err := tx.Where("1 = 1").Delete(&group.GroupHistoryDetail{}).Error; err != nil {
			l.Errorw("Failed to clear group history details", logger.Field("error", err.Error()))
			return err
		}
		l.Infow("Successfully cleared group history details")

		// 7. Delete all group config settings
		if err := tx.Where("`category` = ?", "group").Delete(&system.System{}).Error; err != nil {
			l.Errorw("Failed to delete group config", logger.Field("error", err.Error()))
			return err
		}
		l.Infow("Successfully deleted all group config settings")

		return nil
	})
	if err != nil {
		return err
	}

	l.Infow("Group reset completed successfully")
	return nil
}
