package main

import (
	"context"
	"log"
	"net/http"
	"os"

	"logjensticks/internal/auth"
	"logjensticks/internal/db"
)

func main() {
	mongoURI := os.Getenv("MONGO_URI")
	if mongoURI == "" {
		mongoURI = "mongodb://localhost:27017/logjensticks"
	}

	// In production set COOKIE_SECURE=true (requires HTTPS).
	// Defaults to false for local dev over HTTP.
	secureCookie := os.Getenv("COOKIE_SECURE") == "true"

	ctx := context.Background()

	dbClient, err := db.Connect(ctx, mongoURI)
	if err != nil {
		log.Fatalf("db: failed to connect: %v", err)
	}
	defer dbClient.Disconnect(ctx)

	if err := dbClient.EnsureIndexes(ctx); err != nil {
		log.Fatalf("db: failed to create indexes: %v", err)
	}

	seedUsername := os.Getenv("SEED_USERNAME")
	seedPassword := os.Getenv("SEED_PASSWORD")
	if seedUsername == "" {
		seedUsername = "broker"
		log.Println("WARNING: SEED_USERNAME not set, using dev default 'broker'")
	}
	if seedPassword == "" {
		seedPassword = "changeme"
		log.Println("WARNING: SEED_PASSWORD not set, using dev default 'changeme'")
	}
	if err := dbClient.SeedBroker(ctx, seedUsername, seedPassword); err != nil {
		log.Fatalf("db: seed failed: %v", err)
	}

	protected := auth.Middleware(dbClient)

	mux := http.NewServeMux()
	mux.HandleFunc("/health", handleHealth)
	mux.HandleFunc("/login", handleLogin(dbClient, secureCookie))
	mux.HandleFunc("/logout", handleLogout(dbClient, secureCookie))
	mux.Handle("/me", protected(http.HandlerFunc(handleMe)))

	addr := ":8080"
	log.Printf("server starting on %s", addr)
	if err := http.ListenAndServe(addr, mux); err != nil {
		log.Fatalf("server error: %v", err)
	}
}

func handleHealth(w http.ResponseWriter, r *http.Request) {
	w.Header().Set("Content-Type", "application/json")
	w.WriteHeader(http.StatusOK)
	w.Write([]byte(`{"success":true}`))
}
