// Command zfs-server is the main entry point for the ZFS snapshot backup server.
// It initializes the server with S3 or local storage and starts the HTTP API.
package main

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

	"git.ma-al.com/goc_marek/zfs/internal/server"
)

func main() {
	// Load configuration from .env file and environment
	cfg := server.LoadConfig()

	// Initialize backends
	var s3Backend *server.S3Backend
	var err error

	if cfg.S3Enabled {
		s3Backend, err = server.NewS3Backend(cfg.S3Endpoint, cfg.S3AccessKey, cfg.S3SecretKey, cfg.S3BucketName, cfg.S3UseSSL)
		if err != nil {
			log.Fatalf("Failed to initialize S3 backend: %v", err)
		}
		log.Printf("Initialized S3 backend: %s/%s", cfg.S3Endpoint, cfg.S3BucketName)
	} else {
		log.Println("S3 backend disabled, using local ZFS storage only")
	}

	localBackend := server.NewLocalBackend(cfg.BaseDataset)

	// Initialize server with SQLite database
	srv, err := server.New(cfg.DatabasePath, s3Backend, localBackend)
	if err != nil {
		log.Fatalf("Failed to initialize server: %v", err)
	}
	defer srv.Close()

	// Register HTTP routes
	mux := http.NewServeMux()
	srv.RegisterRoutes(mux)

	// Create HTTP server with timeouts for security and reliability
	// Note: ReadTimeout is set high to allow streaming uploads where data
	// may come in bursts (zfs send can pause between chunks)
	httpServer := &http.Server{
		Addr:         ":" + cfg.Port,
		Handler:      mux,
		ReadTimeout:  30 * time.Minute,  // Allow streaming uploads with pauses
		WriteTimeout: 30 * time.Minute,  // Allow large file downloads
		IdleTimeout:  120 * time.Second, // Close idle connections
	}

	log.Printf("ZFS Snapshot Server starting on port %s", cfg.Port)
	log.Printf("Database: %s", cfg.DatabasePath)
	log.Printf("S3 enabled: %v", cfg.S3Enabled)

	if err := httpServer.ListenAndServe(); err != nil {
		log.Fatal(err)
	}
}
