package main

import (
	"github.com/gin-gonic/gin"
	"github.com/joho/godotenv"
	"log"
	"net/http"
	"os"
	"resource_manager/cache"
	"resource_manager/resource"
	"strings"
	"time"
)

func init() {
	log.SetPrefix("[ReM] ")
	godotenv.Load()
}

func main() {
	cacheManager := cache.NewManager()
	expiration := loadExpiration()
	log.Println("Presign | expiration set to " + expiration.String())

	resourceManager := resource.NewManager(cacheManager, expiration)

	server := gin.Default()
	if strings.Contains(os.Getenv("PROFILE"), "legacy") {
		setupLegacyEndpoints(server, resourceManager)
	}
	setupV1Endpoints(server, resourceManager)
	log.Fatalln(http.ListenAndServe(":5201", server))
}

func loadExpiration() time.Duration {
	if value := os.Getenv("PRESIGN_DURATION"); value != "" {
		duration, err := time.ParseDuration(value)
		if err != nil {
			return duration
		}
	}
	// default duration
	return 1 * time.Hour
}

func setupLegacyEndpoints(server *gin.Engine, resourceManager resource.Manager) {
	server.POST("/save", HandleLegacySave(resourceManager))
	server.GET("/get", HandleGet(resourceManager))
	server.GET("/presign", HandlePresign(resourceManager))
	server.PUT("/copy", HandleCopy(resourceManager))
}

func setupV1Endpoints(server *gin.Engine, resourceManager resource.Manager) {
	server.POST("/api/v1/save", HandleLegacySave(resourceManager))
	server.GET("/api/v1/get", HandleGet(resourceManager))
	server.GET("/api/v1/presign", HandlePresign(resourceManager))
	server.PUT("/api/v1/copy", HandleCopy(resourceManager))
	server.DELETE("/api/v1/delete", HandleDelete(resourceManager))
}
