package server

import (
	"context"

	"github.com/gin-gonic/gin"

	"gitstore.ru/tolikproh/sirius/internal/controller/handler"

	"log"
	"net/http"
	"os"
	"os/signal"
	"time"
)

type App struct {
	httpServer *http.Server
}

func NewApp(port string) *App {
	// Initiate an S3 compatible client

	return &App{
		httpServer: &http.Server{
			Addr:           ":" + port,
			ReadTimeout:    10 * time.Second,
			WriteTimeout:   10 * time.Second,
			MaxHeaderBytes: 1 << 20,
		}}
}

func (a *App) Run() error {
	// Init gin handler
	router := gin.Default()

	router.Use(
		gin.Recovery(),
		gin.Logger(),
	)

	// API endpoints
	api := router.Group("/api")
	api.POST("/upload", handler.Upload)

	// HTTP Server
	a.httpServer.Handler = router

	go func() {
		if err := a.httpServer.ListenAndServe(); err != nil {
			log.Fatalf("Failed to listen and serve: %+v", err)
		}
	}()

	quit := make(chan os.Signal, 1)
	signal.Notify(quit, os.Interrupt, os.Interrupt)

	<-quit

	ctx, shutdown := context.WithTimeout(context.Background(), 5*time.Second)
	defer shutdown()

	return a.httpServer.Shutdown(ctx)
}
