package main

import (
	"flag"
	"log"
	"os"

	"gophergate/internal/config"
	"gophergate/internal/db"
	"gophergate/internal/server"

	"github.com/joho/godotenv"
	"golang.org/x/crypto/bcrypt"
)

func main() {
	resetAdmin := flag.Bool("reset-admin", false, "Reset admin password to admin123")
	flag.Parse()

	// Load environment variables
	if err := godotenv.Load(); err != nil {
		log.Println("No .env file found")
	}

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

	// Initialize database
	database, err := db.Init(cfg.Database.Path)
	if err != nil {
		log.Fatalf("Failed to initialize database: %v", err)
	}

	if *resetAdmin {
		hash, _ := bcrypt.GenerateFromPassword([]byte("admin123"), 12)
		_, err = database.Exec("UPDATE users SET password_hash = ?, must_change_password = 1 WHERE username = 'admin'", string(hash))
		if err != nil {
			log.Fatalf("Failed to reset admin password: %v", err)
		}
		log.Println("Admin password has been reset to 'admin123'")
		os.Exit(0)
	}

	// Initialize server
	s := server.NewServer(cfg, database)

	// Run server
	log.Printf("Starting GopherGate on %s:%d", cfg.Server.Host, cfg.Server.Port)
	if err := s.Run(); err != nil {
		log.Fatalf("Server failed: %v", err)
	}
}
