package main

import (
	"log"
	"whereismymoney/internal/config"
	"whereismymoney/internal/database"
	"whereismymoney/internal/handlers"

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

func main() {
	// Load configuration
	cfg, err := config.Load()
	if err != nil {
		log.Fatal("Fehler beim Laden der Konfiguration:", err)
	}

	// Connect to database
	db, err := database.Connect(cfg)
	if err != nil {
		log.Fatal("Fehler beim Verbinden zur Datenbank:", err)
	}

	// Initialize handlers
	h := handlers.NewHandler(db)

	// Setup Gin router
	r := gin.Default()
	
	// Statische Dateien servieren
	r.Static("/static", "./static")
	
	// Auth Routes
	r.GET("/login", h.ShowLogin)
	r.POST("/login", h.Login)
	r.GET("/register", h.ShowRegister)
	r.POST("/register", h.Register)
	r.POST("/logout", h.Logout)
	
	// Protected Routes
	r.GET("/", h.Dashboard)
	r.GET("/api/dashboard-data", h.DashboardDataAPI)
	r.GET("/accounts", h.ShowAccounts)
	r.POST("/accounts/bank", h.CreateBankAccount)
	r.POST("/accounts/depot", h.CreateDepot)
	
	// Test Route für wiederkehrende Transaktionen
	r.GET("/test/recurring", h.TestRecurringTransactions)
	
	// Transaction Routes
	r.GET("/transactions", h.ShowTransactions)
	r.POST("/transactions", h.CreateTransaction)
	r.POST("/transactions/recurring", h.CreateRecurringTransaction)
	r.DELETE("/transactions/:id", h.DeleteTransaction)
	r.GET("/transactions/:id/data", h.GetTransactionData)
	r.PUT("/transactions/:id", h.UpdateTransaction)
	r.PUT("/transactions/multi-update", h.MultiUpdateTransactions)
	r.DELETE("/transactions/multi-delete", h.MultiDeleteTransactions)
	r.POST("/transactions/recurring/:id/toggle", h.ToggleRecurrenceRule)
	
	// Recurring Transactions Management
	r.GET("/recurring", h.ShowRecurringTransactions)
	
	// Recurring Transaction Management Routes
	r.GET("/api/recurring-rules", h.GetRecurrenceRules)
	r.PUT("/api/recurring-rules/:id", h.UpdateRecurrenceRule)
	r.DELETE("/api/recurring-rules/:id", h.DeleteRecurrenceRule)

	// Settings Routes
	r.GET("/settings", h.ShowSettings)
	r.PUT("/settings/user", h.UpdateUserSettings)
	r.PUT("/settings/password", h.UpdatePassword)
	r.POST("/settings/categories", h.CreateCategory)
	r.DELETE("/settings/categories/:id", h.DeleteCategory)
	r.DELETE("/settings/accounts/:id", h.DeleteBankAccount)

	addr := cfg.Server.Host + ":" + cfg.Server.Port
	log.Printf("Server startet auf %s...", addr)
	log.Printf("Öffne http://%s in deinem Browser", addr)
	
	if err := r.Run(":" + cfg.Server.Port); err != nil {
		log.Fatal("Server konnte nicht gestartet werden:", err)
	}
}
