package main

import (
	"embed"
	"fitra-backend/application"
	"fitra-backend/controllers"
	"fmt"
	"html/template"
	"io/fs"
	"log"
	"net/http"
	"os"

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

//go:embed views/*
var viewsFS embed.FS

//go:embed static/*
var staticFS embed.FS

func main() {
	if err := godotenv.Load(); err != nil {
		log.Println("No .env file found")
	}

	go application.StartCleanupRoutine()

	r := gin.Default()

	tmpl := template.Must(template.New("").ParseFS(viewsFS, "views/*.html", "views/partials/*.html"))
	r.SetHTMLTemplate(tmpl)

	staticSub, _ := fs.Sub(staticFS, "static")
	r.StaticFS("/static", http.FS(staticSub))

	r.GET("/", controllers.HandleIndex)
	r.POST("/upload", controllers.HandleFileUpload)
	r.GET("/uploads/:fileID/:filename", controllers.HandleFileDownload)
	r.GET("/storage", controllers.HandleStorageInfo)
	r.GET("/health", func(c *gin.Context) { c.JSON(200, gin.H{"status": "ok"}) })

	if port := os.Getenv("PORT"); port != "" {
		fmt.Printf("FITRA Backend starting on port %s\n", port)
		r.Run(":" + port)
	} else {
		fmt.Println("FITRA Backend starting on port 8080")
		r.Run(":8080")
	}
}
