package web_console

import (
	"encoding/json"
	"fmt"
	"net/http"
	"time"

	"github.com/pingcap-inc/labs.tidb.io/ssh-proxy/internal/config"

	"github.com/pingcap/log"
	"go.uber.org/zap"
)

func StartHttpServer(cfg *config.Config) {
	server := newHTTPServer(cfg)

	log.Info("Starting server on port", zap.Int("port", cfg.HttpPort))
	if err := server.ListenAndServe(); err != nil {
		log.Fatal("failed to start server", zap.Error(err))
	}
}

func newHTTPServer(cfg *config.Config) *http.Server {
	handler := &sshHandler{
		jwtPublicKey:     cfg.JwtPublicKey,
		sshIdentityFiles: cfg.SshIdentityFiles,
	}

	mux := http.NewServeMux()
	if cfg.Debug {
		mux.Handle("/", http.FileServer(http.Dir("./frontend/")))
	}
	mux.HandleFunc("/ssh-server/web", handler.webSocket)
	mux.HandleFunc("/health", func(w http.ResponseWriter, r *http.Request) {
		w.Header().Set("Content-Type", "application/json")
		w.WriteHeader(http.StatusOK)
		_ = json.NewEncoder(w).Encode(map[string]string{"message": "I'm alive"})
	})

	return &http.Server{
		Addr:              fmt.Sprintf(":%d", cfg.HttpPort),
		Handler:           mux,
		ReadHeaderTimeout: 5 * time.Second,
		IdleTimeout:       60 * time.Second,
	}
}
