package api

import (
	"net/http"

	"devone.aplikasi.web.id/gitea/mario/go-ohif-proxy/config"
	"devone.aplikasi.web.id/gitea/mario/go-ohif-proxy/internal/api/handlers"
	apiMiddleware "devone.aplikasi.web.id/gitea/mario/go-ohif-proxy/internal/api/middleware"
	"devone.aplikasi.web.id/gitea/mario/go-ohif-proxy/internal/auth"
	"devone.aplikasi.web.id/gitea/mario/go-ohif-proxy/internal/proxy"
	"github.com/go-chi/chi/v5"
	"github.com/go-chi/chi/v5/middleware"
	"github.com/go-chi/cors"
	"go.uber.org/zap"
)

// SetupRouter configures and returns the API router
func SetupRouter(cfg *config.Config, logger *zap.Logger) http.Handler {
	r := chi.NewRouter()

	// Built-in Chi middleware
	r.Use(middleware.RequestID)
	r.Use(middleware.RealIP)
	r.Use(middleware.Recoverer)
	r.Use(middleware.StripSlashes)

	// Custom middleware
	r.Use(apiMiddleware.Logger(logger))

	// CORS middleware
	r.Use(cors.Handler(cors.Options{
		AllowedOrigins:   cfg.AllowedOrigins,
		AllowedMethods:   []string{"GET", "POST", "PUT", "DELETE", "OPTIONS"},
		AllowedHeaders:   []string{"Accept", "Authorization", "Content-Type", "X-CSRF-Token"},
		ExposedHeaders:   []string{"Link"},
		AllowCredentials: true,
		MaxAge:           300,
	}))

	// Setup health check
	r.Get("/health", handlers.HealthCheck)

	// Initialize Google auth client
	googleAuth, err := auth.NewGoogleClient(cfg.Google.CredentialsPath)
	if err != nil {
		logger.Fatal("Failed to initialize Google auth client", zap.Error(err))
	}

	// Initialize Healthcare API client
	healthcareClient := proxy.NewClient(googleAuth, cfg.Google)

	// DICOM Web routes - simplified approach
	r.Route("/dicomWeb", func(r chi.Router) {
		// Add audit logging middleware to DICOM routes
		r.Use(apiMiddleware.AuditLog(logger))

		// Create single handler for all DICOM requests
		dicomHandler := handlers.NewDicomHandler(healthcareClient, logger)

		// Catch all routes under /dicomWeb and forward them
		r.HandleFunc("/*", dicomHandler.ForwardRequest)
	})

	// Future auth routes for doctors
	r.Route("/auth", func(r chi.Router) {
		authHandler := handlers.NewAuthHandler(logger)
		r.Post("/login", authHandler.Login)
		r.Post("/logout", authHandler.Logout)
	})

	return r
}
