package main

import (
	"encoding/hex"
	"flag"
	"log"
	"time"

	"git.godopu.com/lab/landing_page/backend/internal/config"
	"git.godopu.com/lab/landing_page/backend/internal/db"
	"git.godopu.com/lab/landing_page/backend/internal/router"
	"github.com/gin-gonic/gin"
)

func main() {
	// Load environment variables & .env
	cfg := config.Load()

	// Optional CLI flags override environment defaults
	portFlag := flag.Int("port", 0, "Port for the Gin server to listen on (overrides PORT)")
	hostFlag := flag.String("host", "", "Host for the Gin server to bind on (overrides HOST)")
	dbPathFlag := flag.String("db", "", "Path to SQLite database file (overrides DB_PATH)")
	ginModeFlag := flag.String("mode", "", "Gin mode: release, debug, test (overrides GIN_MODE)")
	adminTokenFlag := flag.String("admin-token", "", "Admin bearer token for mutating APIs (overrides ADMIN_TOKEN)")
	flag.Parse()

	if *portFlag > 0 {
		cfg.Port = *portFlag
	}
	if *hostFlag != "" {
		cfg.Host = *hostFlag
	}
	if *dbPathFlag != "" {
		cfg.DBPath = *dbPathFlag
	}
	if *ginModeFlag != "" {
		cfg.GinMode = *ginModeFlag
	}
	if *adminTokenFlag != "" {
		cfg.AdminToken = *adminTokenFlag
	}

	if cfg.AdminToken == "" {
		if cfg.GinMode == gin.ReleaseMode || cfg.GinMode == "release" {
			log.Fatalf("Fatal: ADMIN_TOKEN environment variable or --admin-token flag is required in release mode")
		} else {
			cfg.AdminToken = "dev-ephemeral-" + hex.EncodeToString([]byte(time.Now().Format("20060102150405")))
			log.Printf("⚠️ WARNING: ADMIN_TOKEN not configured. Generated ephemeral dev token: %s", cfg.AdminToken)
		}
	}

	gin.SetMode(cfg.GinMode)

	log.Printf("Connecting to SQLite database at %s...", cfg.DBPath)
	database, err := db.Connect(cfg.DBPath)
	if err != nil {
		log.Fatalf("Failed to connect to database: %v", err)
	}
	defer database.Close()

	if cfg.AutoMigrate {
		log.Println("Ensuring database schema migrations are applied...")
		if err := db.RunMigrations(database); err != nil {
			log.Fatalf("Migration failed: %v", err)
		}
	}

	r := router.SetupRouter(database, cfg.AdminToken, cfg.CORSAllowOrigins)

	addr := cfg.Address()
	log.Printf("Starting ANL Backend API server on http://%s/api/v1 (mode: %s)...", addr, cfg.GinMode)
	if err := r.Run(addr); err != nil {
		log.Fatalf("Server failed to run: %v", err)
	}
}
