package main

import (
	"log"

	"photum-backend/internal/auth"
	"photum-backend/internal/config"
	"photum-backend/internal/db"
	"photum-backend/internal/funcoes"
	"photum-backend/internal/profissionais"

	"github.com/gin-gonic/gin"
	swaggerFiles "github.com/swaggo/files"
	ginSwagger "github.com/swaggo/gin-swagger"

	_ "photum-backend/docs" // Import generated docs
)

// @title           Photum Backend API
// @version         1.0
// @description     Backend authentication service for Photum.
// @termsOfService  http://swagger.io/terms/

// @contact.name    API Support
// @contact.url     http://www.swagger.io/support
// @contact.email   support@swagger.io

// @license.name    Apache 2.0
// @license.url     http://www.apache.org/licenses/LICENSE-2.0.html

// @host            localhost:8080
// @BasePath        /

// @securityDefinitions.apikey BearerAuth
// @in header
// @name Authorization
func main() {
	cfg := config.LoadConfig()
	log.Printf("Loaded DSN: %s", cfg.DBDsn)

	queries, pool := db.Connect(cfg)
	defer pool.Close()

	// Initialize services
	profissionaisService := profissionais.NewService(queries)
	authService := auth.NewService(queries, profissionaisService, cfg)
	funcoesService := funcoes.NewService(queries)

	// Initialize handlers
	authHandler := auth.NewHandler(authService)
	profissionaisHandler := profissionais.NewHandler(profissionaisService)
	funcoesHandler := funcoes.NewHandler(funcoesService)

	r := gin.Default()

	// Swagger
	r.GET("/swagger/*any", ginSwagger.WrapHandler(swaggerFiles.Handler))

	// Public Routes
	authGroup := r.Group("/auth")
	{
		authGroup.POST("/register", authHandler.Register)
		authGroup.POST("/login", authHandler.Login)
		authGroup.POST("/refresh", authHandler.Refresh)
		authGroup.POST("/logout", authHandler.Logout)
	}

	// Public API Routes
	r.GET("/api/funcoes", funcoesHandler.List)

	// Protected Routes
	api := r.Group("/api")
	api.Use(auth.AuthMiddleware(cfg))
	{
		api.GET("/me", func(c *gin.Context) {
			userID, _ := c.Get("userID")
			role, _ := c.Get("role")
			c.JSON(200, gin.H{
				"user_id": userID,
				"role":    role,
				"message": "You are authenticated",
			})
		})

		profGroup := api.Group("/profissionais")
		{
			profGroup.POST("", profissionaisHandler.Create)
			profGroup.GET("", profissionaisHandler.List)
			profGroup.GET("/:id", profissionaisHandler.Get)
			profGroup.PUT("/:id", profissionaisHandler.Update)
			profGroup.DELETE("/:id", profissionaisHandler.Delete)
		}

		funcoesGroup := api.Group("/funcoes")
		{
			funcoesGroup.POST("", funcoesHandler.Create)
			// GET is now public
			funcoesGroup.PUT("/:id", funcoesHandler.Update)
			funcoesGroup.DELETE("/:id", funcoesHandler.Delete)
		}
	}

	log.Printf("Server running on port %s", cfg.AppPort)
	r.Run(":" + cfg.AppPort)
}
