package main

import (
	"fmt"
	"log"
	"os"
	"os/signal"
	"syscall"

	"fred-api/config"
	"fred-api/handlers"

	"github.com/gin-gonic/gin"
	"github.com/joho/godotenv"
)

func main() {
	if err := godotenv.Load(); err != nil {
		log.Println("No .env file found, using default config")
	}

	cfg := config.Load()

	fredHandler := handlers.NewFREDHandler(cfg)

	gin.SetMode(gin.ReleaseMode)
	router := gin.Default()

	router.Use(func(c *gin.Context) {
		c.Header("Access-Control-Allow-Origin", "*")
		c.Header("Access-Control-Allow-Methods", "GET, POST, OPTIONS")
		c.Header("Access-Control-Allow-Headers", "Content-Type, Authorization")
		if c.Request.Method == "OPTIONS" {
			c.AbortWithStatus(204)
			return
		}
		c.Next()
	})

	router.GET("/health", fredHandler.HealthCheck)

	api := router.Group("/api/v1")
	{
		api.GET("/series", fredHandler.GetSeries)
		api.GET("/series/observations", fredHandler.GetObservations)
		api.GET("/series/search", fredHandler.SearchSeries)
		api.GET("/releases", fredHandler.GetReleases)
		api.GET("/releases/dates", fredHandler.GetReleaseDates)
		api.GET("/release/series", fredHandler.GetReleaseSeries)
	}

	go func() {
		fmt.Printf("FRED API Server starting on :%s\n", cfg.ServerPort)
		fmt.Printf("FRED API Base URL: %s\n", cfg.FREDBaseURL)
		fmt.Println("\nAvailable endpoints:")
		fmt.Println("  GET /health              - Health check")
		fmt.Println("  GET /api/v1/series                    - Get series info")
		fmt.Println("  GET /api/v1/series/observations       - Get observations")
		fmt.Println("  GET /api/v1/series/search             - Search series")
		fmt.Println("  GET /api/v1/releases                  - Get all releases")
		fmt.Println("  GET /api/v1/releases/dates            - Get release dates")
		fmt.Println("  GET /api/v1/release/series            - Get series in release")
		fmt.Println("")
		fmt.Println("Examples:")
		fmt.Println("  curl 'http://localhost:" + cfg.ServerPort + "/api/v1/series?series_id=GNPCA'")
		fmt.Println("  curl 'http://localhost:" + cfg.ServerPort + "/api/v1/series/observations?series_id=GNPCA&limit=10'")
		fmt.Println("  curl 'http://localhost:" + cfg.ServerPort + "/api/v1/series/search?search_text=GDP'")
		fmt.Println("")

		if err := router.Run(":" + cfg.ServerPort); err != nil {
			log.Fatalf("Failed to start server: %v", err)
		}
	}()

	quit := make(chan os.Signal, 1)
	signal.Notify(quit, syscall.SIGINT, syscall.SIGTERM)
	<-quit

	fmt.Println("\nShutting down server...")
}
