// scripts/migrate_existing_users.go
package main

import (
	"api_bb/internal/models"
	"api_bb/internal/repository"
	"api_bb/pkg/logger"

	"gorm.io/gorm"
	"go.uber.org/zap"
)

func MigrateExistingUsers(db *gorm.DB) error {
	log := logger.NewWrapper(logger.Get().With(zap.String("script", "migrate_existing_users")))
	
	userRepo := repository.NewUserRepository(db)
	userStatsRepo := repository.NewUserStatsRepository(db)

	// Получаем всех пользователей
	users, err := userRepo.FindAll()
	if err != nil {
		return err
	}

	log.Info("starting migration for existing users", 
		zap.Int("total_users", len(users)))

	successCount := 0
	for _, user := range users {
		// Проверяем, есть ли уже статистика
		_, err := userStatsRepo.GetByUserID(user.ID)
		if err == gorm.ErrRecordNotFound {
			// Создаем статистику
			userStats := &models.UserStats{
				UserID:          user.ID,
				TotalDistance:   0,
				TotalTime:       0,
				AvgPace:         "0:00",
				WorkoutsCount:   0,
				CurrentStreak:   0,
				LongestStreak:   0,
				WeeklyDistance:  0,
				MonthlyDistance: 0,
				Best5K:          "",
				Best10K:         "",
				BestHalf:        "",
				BestMarathon:    "",
				LastWorkout:     user.CreatedAt, // Используем дату создания как последнюю тренировку
			}
			
			if err := userStatsRepo.Create(userStats); err != nil {
				log.Error("failed to create stats for user",
					zap.Uint("user_id", user.ID),
					zap.Error(err))
				continue
			}
			
			successCount++
			log.Info("created stats for user", 
				zap.Uint("user_id", user.ID),
				zap.String("email", user.Email))
		} else if err != nil {
			log.Error("error checking stats for user",
				zap.Uint("user_id", user.ID),
				zap.Error(err))
		}
	}

	log.Info("migration completed", 
		zap.Int("successful_creations", successCount),
		zap.Int("total_users", len(users)))

	return nil
}