package main

import (
	"context"
	"flag"
	"fmt"
	"log"

	"github.com/timetracker/backend/internal/config"
	"github.com/timetracker/backend/internal/db"
	"github.com/timetracker/backend/internal/models"
	"gorm.io/gorm"
)

func main() {
	// Parse CLI flags
	_ = flag.String("config", "", "Path to .env config file")
	flag.Parse()

	// Load configuration
	cfg, err := config.LoadConfig()
	if err != nil {
		log.Fatalf("Failed to load config: %v", err)
	}

	// Initialize database
	if err := db.InitDB(cfg.Database); err != nil {
		log.Fatalf("Error initializing database: %v", err)
	}
	defer func() {
		if err := db.CloseDB(); err != nil {
			log.Printf("Error closing database connection: %v", err)
		}
	}()

	// Execute seed operation
	if err := seedDatabase(context.Background()); err != nil {
		log.Fatalf("Error seeding database: %v", err)
	}

	log.Println("Database seeding completed successfully")
}

// seedDatabase performs the database seeding operation
func seedDatabase(ctx context.Context) error {
	// Check if seeding is needed
	var count int64
	if err := db.GetEngine(ctx).Model(&models.Company{}).Count(&count).Error; err != nil {
		return fmt.Errorf("error checking if seeding is needed: %w", err)
	}

	// If data exists, skip seeding
	if count > 0 {
		log.Println("Database already contains data, skipping seeding")
		return nil
	}

	log.Println("Seeding database with initial data...")

	// Start transaction
	return db.GetEngine(ctx).Transaction(func(tx *gorm.DB) error {
		// Create default company
		defaultCompany := models.Company{
			Name: "Default Company",
		}
		if err := tx.Create(&defaultCompany).Error; err != nil {
			return fmt.Errorf("error creating default company: %w", err)
		}

		// Create admin user
		adminUser := models.User{
			Email:      "admin@example.com",
			Role:       models.RoleAdmin,
			CompanyID:  &defaultCompany.ID,
			HourlyRate: 100.0,
		}

		// Hash password
		pwData, err := models.HashPassword("Admin@123456")
		if err != nil {
			return fmt.Errorf("error hashing password: %w", err)
		}

		adminUser.Salt = pwData.Salt
		adminUser.Hash = pwData.Hash

		if err := tx.Create(&adminUser).Error; err != nil {
			return fmt.Errorf("error creating admin user: %w", err)
		}

		return nil
	})
}
