package main

import (
	"context"
	"fmt"
	"log"
	"net/http"
	"time"

	"github.com/emersion/go-webdav/caldav"
	"nxcaldav/internal/backend"
	"nxcaldav/internal/config"
)

func main() {
	cfg, err := config.Load("config.yaml")
	if err != nil {
		log.Fatalf("failed to load config: %v", err)
	}

	ctx := context.Background()
	be, err := backend.NewDBBackend(ctx, cfg)
	if err != nil {
		log.Fatalf("failed to initialize database backend: %v", err)
	}

	handler := &caldav.Handler{Backend: be}

	http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
		user, password, ok := r.BasicAuth()
		if !ok {
			w.Header().Set("WWW-Authenticate", `Basic realm="CalDAV Server"`)
			http.Error(w, "Unauthorized", http.StatusUnauthorized)
			return
		}

		// Verify user against database (bcrypt)
		valid, err := be.VerifyUser(r.Context(), user, password)
		if err != nil {
			log.Printf("auth error for %s: %v", user, err)
			http.Error(w, "Internal Server Error", http.StatusInternalServerError)
			return
		}

		if !valid {
			http.Error(w, "Unauthorized", http.StatusUnauthorized)
			return
		}

		log.Printf("%s %s %s", user, r.Method, r.URL.Path)

		principalPath := fmt.Sprintf("/%s/", user)
		ctx := context.WithValue(r.Context(), "principal", principalPath)

		if r.URL.Path == "/.well-known/caldav" {
			http.Redirect(w, r, principalPath, http.StatusMovedPermanently)
			return
		}

		handler.ServeHTTP(w, r.WithContext(ctx))
	})

	fmt.Printf("Starting CalDAV server on %s...\n", cfg.Server.BindAddress)
	server := &http.Server{
		Addr:         cfg.Server.BindAddress,
		ReadTimeout:  5 * time.Second,
		WriteTimeout: 10 * time.Second,
	}
	if err := server.ListenAndServe(); err != nil {
		log.Fatalf("server failed: %v", err)
	}
}
