package http

import (
	"context"
	"golang.source-fellows.com/training-fellow/booking/internal"
	"log"
	"net/http"
	"time"

	"github.com/gin-gonic/gin"
)

type Config struct {
	Binding string `envconfig:"SERVER_BINDING" required:"true"`
}

func StartServer(serverCtx context.Context, config Config, service *internal.TrainingListingService) error {

	internalCtx, cancel := context.WithCancel(serverCtx)
	defer cancel()

	r := gin.Default()

	trainingHandler := TrainingHandler{trainingListingService: service}

	r.GET("/ping", handlePing)
	r.GET("/trainings", AvailabilityMiddleware(), trainingHandler.GetAllTrainings)

	srv := &http.Server{
		Addr:    config.Binding,
		Handler: r.Handler(),
	}

	go func() {
		<-internalCtx.Done()
		log.Println("server shutdown")
		ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
		defer cancel()
		srv.Shutdown(ctx)
	}()

	err := srv.ListenAndServe()
	if err != nil {
		log.Println(err)
		cancel()
	}

	return err
}

func handlePing(context *gin.Context) {
	context.Data(http.StatusOK, "text/plain", []byte("pong"))
}
