package main

import (
	"fmt"
	"net/http"
	"os"

	"portfolio-tracker/internal/handler"
	"portfolio-tracker/internal/model"

	"github.com/glebarez/sqlite"
	"gorm.io/gorm"
	"gorm.io/gorm/logger"
)

func main() {
	// Create data directory if it doesn't exist
	if err := os.MkdirAll("data", 0755); err != nil {
		panic("failed to create data directory: " + err.Error())
	}

	dbPath := "data/portfolio.db"
	fmt.Printf("Opening database at: %s\n", dbPath)

	db, err := gorm.Open(sqlite.Open(dbPath), &gorm.Config{
		Logger: logger.Default.LogMode(logger.Error),
	})

	// Set the global DB variable for the handlers
	handler.DB = db

	// Auto-migrate all models
	err = db.AutoMigrate(
		&model.User{},
		&model.Portfolio{},
		&model.Activity{},
	)
	if err != nil {
		panic("failed to migrate database: " + err.Error())
	}

	fmt.Println("Database migrations completed successfully")

	// Routes - organized by functionality

	// Main pages
	http.HandleFunc("/", handler.Handler)
	http.HandleFunc("/details", handler.DetailsHandler)

	// API endpoints
	http.HandleFunc("/api/yahoo", handler.JsonEndpoint)
	http.HandleFunc("/api/yahoomaxdividends", handler.YahooMaxDividendsHandler)
	http.HandleFunc("/api/stocksearch", handler.StockSearchEndpoint)

	// Admin endpoints
	http.HandleFunc("/api/admin/clear-currency-cache", handler.ClearCurrencyCacheHandler)
	http.HandleFunc("/api/admin/clean-expired-cache", handler.CleanExpiredCacheHandler)
	http.HandleFunc("/api/admin/currency-cache-info", handler.CurrencyCacheInfoHandler)

	// Authentication
	http.HandleFunc("/user/register", handler.RegisterHandler)
	http.HandleFunc("/user/login", handler.LoginHandler)
	http.HandleFunc("/user/logout", handler.LogoutHandler)

	// Portfolio management
	http.HandleFunc("/portfolio", handler.PortfolioHandler)
	http.HandleFunc("/portfolio/create", handler.CreatePortfolioHandler)
	http.HandleFunc("/portfolio/transaction", handler.PortfolioTransactionHandler)
	http.HandleFunc("/portfolio/transaction/edit", handler.EditTransactionHandler)
	http.HandleFunc("/portfolio/transaction/delete", handler.DeleteTransactionHandler)
	http.HandleFunc("/portfolio/", handler.PortfolioDetailHandler) // Note the trailing slash

	fmt.Println("Server läuft auf http://localhost:8080")
	http.ListenAndServe(":8080", nil)
}
