package main

import (
	"ashareview-server/config"
	"ashareview-server/handler"
	"ashareview-server/repository"
	"ashareview-server/router"
	"ashareview-server/service"
	"fmt"
	"log"
	"time"

	"github.com/gin-gonic/gin"
	"gorm.io/driver/mysql"
	"gorm.io/gorm"
)

func main() {
	cfg := config.Load()

	db, err := gorm.Open(mysql.Open(cfg.DB.DSN()), &gorm.Config{})
	if err != nil {
		log.Fatalf("failed to connect database: %v", err)
	}
	fmt.Println("Database connected successfully")

	// Create indexes in background (10M rows, may take minutes)
	go func() {
		time.Sleep(3 * time.Second)
		indexes := []string{
			"ALTER TABLE stock_daily ADD INDEX idx_sd_date (date)",
			"ALTER TABLE stock_daily ADD INDEX idx_sd_code_date (code, date)",
			"ALTER TABLE stock_daily ADD INDEX idx_sd_date_pct (date, pct_change)",
			"ALTER TABLE stock_daily ADD INDEX idx_sd_code_date_close (code, date, close)",
		}
		for _, idx := range indexes {
			if err := db.Exec(idx).Error; err != nil {
				fmt.Printf("index: %v (may already exist)\n", err)
			} else {
				fmt.Printf("index created: %s\n", idx)
			}
		}
	}()

	stockRepo := repository.NewStockRepo(db)
	dashboardSvc := service.NewDashboardService(stockRepo)
	dashboardHandler := handler.NewDashboardHandler(dashboardSvc)

	r := gin.Default()
	router.Setup(r, dashboardHandler)

	addr := fmt.Sprintf(":%s", cfg.Server.Port)
	fmt.Printf("Server running on http://localhost%s\n", addr)
	if err := r.Run(addr); err != nil {
		log.Fatalf("failed to start server: %v", err)
	}
}
