package main

import (
	"log"
	"rrbec_server/internal/api"
	"rrbec_server/internal/config"
	"rrbec_server/internal/database"
	"rrbec_server/internal/repository"
	"rrbec_server/internal/service"
	"rrbec_server/internal/sync"

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

func main() {
	// 1. Load Configuration
	config.LoadConfig()

	// 2. Initialize Database
	db := database.InitDB(config.AppConfig.DBName)

	// 3. Initialize Dependency Injection
	repo := repository.NewRepository(db)
	svc := service.NewService(repo)
	handler := api.NewHandler(svc)

	// 4. Start Sync Worker
	syncer := sync.NewSyncer(repo, config.AppConfig.DjangoBaseURL, config.AppConfig.DjangoMasterUser, config.AppConfig.DjangoMasterPassword)
	handler.SetSyncer(syncer)
	syncer.Start()

	// 4. Setup Gin Router
	r := gin.Default()

	// API Routes
	v1 := r.Group("/api/v1")
	{
		// Public routes
		v1.POST("/login", handler.Login)
		v1.GET("/products", handler.GetProducts)
		v1.GET("/mesas", handler.GetMesas)
		v1.GET("/comandas", handler.GetComandas)
		v1.GET("/comandas/:id", handler.GetComandaByID)
		v1.GET("/categories", handler.GetCategories)
		v1.GET("/payment-types", handler.GetTypePayments)
		v1.GET("/clients", handler.GetClients)
		v1.GET("/orders", handler.GetOrders)
		v1.GET("/payments", handler.GetPayments)

		// Protected routes
		protected := v1.Group("/")
		protected.Use(api.SimpleAuthMiddleware())
		{
			protected.POST("/products", handler.CreateProduct)
			protected.PATCH("/products/:id", handler.UpdateProduct)
			protected.POST("/admin/resync-products", handler.ResyncProducts)
			protected.POST("/categories", handler.CreateCategory)
			protected.PATCH("/categories/:id", handler.UpdateCategory)
			protected.POST("/comandas", handler.CreateComanda)
			protected.POST("/items-comanda", handler.AddItemToComanda)
			protected.DELETE("/items-comanda/:id", handler.DeleteItemFromComanda)
			protected.POST("/comandas/:id/apagar", handler.ClearComanda)
			protected.POST("/comandas/:id/pagar", handler.PagarComanda)
			protected.PATCH("/comandas/:id", handler.UpdateComanda)
			protected.POST("/orders", handler.CreateOrder)
			protected.PATCH("/orders/:id", handler.UpdateOrder)
			protected.POST("/orders/:id/preparing", handler.SetOrderPreparing)
			protected.POST("/orders/:id/finish", handler.SetOrderFinished)
			protected.POST("/orders/:id/deliver", handler.SetOrderDelivered)
			protected.POST("/orders/:id/cancel", handler.SetOrderCanceled)
			protected.GET("/me", handler.GetCurrentUser)
		}
	}

	// 6. Run Server
	log.Printf("Local server running on http://localhost:%s", config.AppConfig.Port)
	if err := r.Run(":" + config.AppConfig.Port); err != nil {
		log.Fatalf("failed to run server: %v", err)
	}
}
