package server

import (
	"net/http"

	"github.com/go-chi/chi/v5"

	"github.com/rjNemo/rentease/internal/service/auth"
)

func (s *Server) MountHandlers() {
	s.Router.Get("/healthz", handleHealthCheck())
	s.Router.Get("/", handleLoginPage())
	s.Router.Post("/", handleLogin(s.as))
	s.Router.Post("/webhooks/stripe", handleStripeWebhook(s.bs, s.stripeWebhookSecret))

	s.Router.Route("/api", func(r chi.Router) {
		r.Use(apiKeyMiddleware(s.as))
		r.Post("/sync", handleSync(s.bs))
		r.Get("/bookings", handleBookingList(s.bs))
		r.Post("/bookings", handleCreateBooking(s.bs))
		r.Post("/stripe/sync", handleStripeSync(s.bs))
	})

	s.Router.Group(func(r chi.Router) {
		r.Use(MakeAuthMiddleware(s.as))

		r.Get("/bookings", handleBookingListPage(s.bs, s.hc))
		r.Get("/bookings/new", handleBookingCreatePage(s.hc))
		r.Post("/bookings/new", handleBookingCreate(s.bs))
		r.Get("/bookings/{id}", handleBookingPage(s.bs, s.hc))
		r.Post("/bookings/{id}/stripe/payment-link", handleBookingStripePaymentLink(s.bs))
		r.Put("/bookings/{id}", handleBookingUpdate(s.bs, s.hc))
		r.Patch("/bookings/{id}/cancel", handleBookingCancel(s.bs))
		r.Post("/bookings/{id}/items", handleCreateItem(s.bs, s.hc))
		r.Get("/bookings/pdf/{id}", handlePdfCreateInvoice(s.bs, s.hc))

		r.Post("/items/{id}", handleItemPay(s.bs))
		r.Put("/items/{id}", handleItemUpdate(s.bs))
		r.Get("/items/{id}", handleLineItemForm(s.bs))

		r.Get("/reports", handleReportsPage())
		r.Get("/reports/do", handleReportCompute(s.bs, s.hc))
		r.Get("/reports/pdf", handlePdfCreateReport(s.bs))

		r.Post("/payments/{id}", handleCreatePayment(s.bs))
		r.Put("/payments/{id}", handlePaymentUpdate(s.bs))
		r.Get("/payments/{id}", handlePaymentForm(s.bs))
	})
}

func apiKeyMiddleware(as *auth.Service) func(http.Handler) http.Handler {
	return func(next http.Handler) http.Handler {
		return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
			if !as.ValidateAPIKey(r.Header.Get("api-key")) {
				http.Error(w, "invalid api key", http.StatusUnauthorized)
				return
			}

			next.ServeHTTP(w, r)
		})
	}
}
