package api

import (
	"log"
	"pki-manager/config"
	"pki-manager/internal/repository"
	"pki-manager/internal/services"

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

func SetupRoutes(router *gin.Engine, repo repository.Repository, jwtSecret string) {
	cfg := config.LoadConfig()
	cryptoService := services.NewCryptoService(cfg.CertsPath)
	handlers := NewHandlers(repo, cryptoService)

	// Add logging middleware
	router.Use(func(c *gin.Context) {
		log.Printf("[API] %s %s", c.Request.Method, c.Request.URL.Path)
		c.Next()
	})

	// Load HTML templates
	router.LoadHTMLGlob("internal/web/templates/*")
	router.Static("/static", "internal/web/static")

	// Web interface
	router.GET("/", handlers.ServeWebInterface)

	// API routes
	api := router.Group("/api/v1")
	{
		// CA routes
		ca := api.Group("/cas")
		{
			ca.POST("/", handlers.CreateCA)
			ca.GET("/", handlers.GetAllCAs)
			ca.GET("/:id", handlers.GetCA)
			ca.PUT("/:id", handlers.UpdateCA)
			ca.DELETE("/:id", handlers.DeleteCA)
			ca.GET("/:id/download/cert", handlers.DownloadCACertificate)
			ca.GET("/:id/download/key", handlers.DownloadCAPrivateKey)

		}

		// SubCA routes
		subca := api.Group("/subcas")
		{
			subca.POST("/", handlers.CreateSubCA)
			subca.GET("/", handlers.GetAllSubCAs)
			subca.GET("/:id", handlers.GetSubCA)
			subca.PUT("/:id", handlers.UpdateSubCA)
			subca.DELETE("/:id", handlers.DeleteSubCA)
			subca.GET("/:id/download/cert", handlers.DownloadSubCACertificate)
			subca.GET("/:id/download/key", handlers.DownloadSubCAPrivateKey)

		}

		// Certificate routes
		cert := api.Group("/certificates")
		{
			cert.POST("/", handlers.CreateCertificate)
			cert.GET("/", handlers.GetAllCertificates)
			cert.GET("/:id", handlers.GetCertificate)
			cert.DELETE("/:id", handlers.DeleteCertificate)
			cert.POST("/:id/revoke", handlers.RevokeCertificate)
			cert.GET("/:id/download/cert", handlers.DownloadCertificate)
			cert.GET("/:id/download/key", handlers.DownloadPrivateKey)
			cert.GET("/:id/download/p12", handlers.DownloadP12)
		}
	}
}
