package main

import (
	"context"
	"fmt"

	"git.warky.dev/wdevs/whatshooked/pkg/api"
	"git.warky.dev/wdevs/whatshooked/pkg/config"
	"git.warky.dev/wdevs/whatshooked/pkg/logging"
	"git.warky.dev/wdevs/whatshooked/pkg/storage"
	"github.com/rs/zerolog/log"
)

// Example: Initialize Phase 2 components and start the API server
func main() {
	// Setup logging
	logging.Init("info")

	// Load configuration
	cfg, err := config.Load("config.json")
	if err != nil {
		log.Fatal().Err(err).Msg("Failed to load configuration")
	}

	// Check if database configuration is provided
	if cfg.Database.Type == "" {
		log.Warn().Msg("No database configuration found, using SQLite default")
		cfg.Database.Type = "sqlite"
		cfg.Database.SQLitePath = "./data/whatshooked.db"
	}

	// Initialize database
	log.Info().
		Str("type", cfg.Database.Type).
		Msg("Initializing database")

	if err := storage.Initialize(&cfg.Database); err != nil {
		log.Fatal().Err(err).Msg("Failed to initialize database")
	}
	defer storage.Close()

	db := storage.GetDB()

	// Create tables using BUN
	log.Info().Msg("Creating database tables")
	if err := storage.CreateTables(context.Background()); err != nil {
		log.Fatal().Err(err).Msg("Failed to create tables")
	}

	// Seed default data (creates admin user if not exists)
	log.Info().Msg("Seeding default data")
	if err := storage.SeedData(context.Background()); err != nil {
		log.Fatal().Err(err).Msg("Failed to seed data")
	}

	// Ensure API config is present
	if !cfg.API.Enabled {
		log.Warn().Msg("API server not enabled in config, enabling with defaults")
		cfg.API.Enabled = true
	}

	// Create API server
	log.Info().Msg("Creating API server with ResolveSpec")
	server, err := api.NewServer(cfg, db)
	if err != nil {
		log.Fatal().Err(err).Msg("Failed to create API server")
	}

	// Start server
	addr := fmt.Sprintf("%s:%d", cfg.API.Host, cfg.API.Port)
	log.Info().
		Str("address", addr).
		Msg("Starting API server")
	log.Info().Msg("Default admin credentials: username=admin, password=admin123")
	log.Info().Msg("⚠️  Please change the default password after first login!")
	log.Info().Msg("")
	log.Info().Msg("API Endpoints:")
	log.Info().Msgf("  - POST %s/api/v1/auth/login   - Login to get JWT token", addr)
	log.Info().Msgf("  - POST %s/api/v1/auth/logout  - Logout and invalidate token", addr)
	log.Info().Msgf("  - GET  %s/api/v1/users        - List users (requires auth)", addr)
	log.Info().Msgf("  - GET  %s/api/v1/hooks        - List hooks (requires auth)", addr)
	log.Info().Msgf("  - GET  %s/health              - Health check", addr)

	// Start the server (blocking call)
	if err := server.Start(); err != nil {
		log.Fatal().Err(err).Msg("API server error")
	}
}
