package api import ( "context" "database/sql" "encoding/json" "net/http" "time" "reanimator/internal/history" "reanimator/internal/ingest" "reanimator/internal/repository/failures" "reanimator/internal/repository/registry" "reanimator/internal/repository/timeline" ) type Server struct { httpServer *http.Server cancelBg context.CancelFunc } func NewServer(addr string, readTimeout, writeTimeout time.Duration, db *sql.DB) *Server { mux := http.NewServeMux() mux.HandleFunc("/health", healthHandler) cancelBg := func() {} if db != nil { bgCtx, cancel := context.WithCancel(context.Background()) cancelBg = cancel failureRepo := failures.NewFailureRepository(db) assetRepo := registry.NewAssetRepository(db) componentRepo := registry.NewComponentRepository(db) installationRepo := registry.NewInstallationRepository(db) timelineRepo := timeline.NewEventRepository(db) historySvc := history.NewService(db) historySvc.StartWorker(bgCtx) RegisterRegistryRoutes(mux, RegistryDependencies{ Assets: assetRepo, Components: componentRepo, History: historySvc, }) RegisterHistoryRoutes(mux, HistoryDependencies{ Service: historySvc, }) RegisterIngestRoutes(mux, IngestDependencies{ Service: ingest.NewService(db), }) RegisterAssetComponentRoutes(mux, AssetComponentDependencies{ Assets: assetRepo, Components: componentRepo, Installations: installationRepo, Timeline: timelineRepo, History: historySvc, }) RegisterFailureRoutes(mux, FailureDependencies{ Failures: failureRepo, }) RegisterUIRoutes(mux, UIDependencies{ Assets: assetRepo, Components: componentRepo, Installations: installationRepo, Timeline: timelineRepo, Failures: failureRepo, }) } return &Server{ httpServer: &http.Server{ Addr: addr, Handler: mux, ReadTimeout: readTimeout, WriteTimeout: writeTimeout, }, cancelBg: cancelBg, } } func (s *Server) Start() error { return s.httpServer.ListenAndServe() } func (s *Server) Shutdown(ctx context.Context) error { if s.cancelBg != nil { s.cancelBg() } return s.httpServer.Shutdown(ctx) } func healthHandler(w http.ResponseWriter, _ *http.Request) { w.Header().Set("Content-Type", "application/json") w.WriteHeader(http.StatusOK) _ = json.NewEncoder(w).Encode(map[string]string{"status": "ok"}) }