package main

import (
	"context"
	"log"
	"net/http"
	"os"

	"github.com/gin-gonic/gin"
	_ "github.com/mattn/go-sqlite3"
	swaggerFiles "github.com/swaggo/files"
	ginSwagger "github.com/swaggo/gin-swagger"

	"gitea.maison43.duckdns.org/gilles/matosbox/docs"
	"gitea.maison43.duckdns.org/gilles/matosbox/internal/data/ent"
	"gitea.maison43.duckdns.org/gilles/matosbox/internal/handlers"
)

// @title MatosBox API
// @version 0.1.0
// @description API MatosBox pour la gestion d'inventaire.
// @BasePath /v1
func main() {
	// Config simple : port via PORT, defaut 8080.
	port := os.Getenv("PORT")
	if port == "" {
		port = "8080"
	}

	r := gin.Default()

	// Connexion base de donnees.
	driver := os.Getenv("DATABASE_DRIVER")
	if driver == "" {
		driver = "sqlite3"
	}
	dsn := os.Getenv("DATABASE_URL")
	if dsn == "" {
		dsn = "file:./data/matosbox.db?_fk=1"
	}

	client, err := ent.Open(driver, dsn)
	if err != nil {
		log.Fatalf("connexion base impossible: %v", err)
	}
	defer func() {
		if err := client.Close(); err != nil {
			log.Printf("fermeture base impossible: %v", err)
		}
	}()

	// Activer WAL pour SQLite si disponible.
	if driver == "sqlite3" {
		if _, err := client.ExecContext(context.Background(), "PRAGMA journal_mode = WAL;"); err != nil {
			log.Printf("activation WAL impossible: %v", err)
		}
	}

	// Auto-creation du schema en dev. A remplacer par migrations en prod.
	if err := client.Schema.Create(context.Background()); err != nil {
		log.Fatalf("creation schema impossible: %v", err)
	}

	// Route de sante pour verifier que le backend repond.
	r.GET("/healthz", func(c *gin.Context) {
		c.JSON(http.StatusOK, gin.H{
			"status":  "ok",
			"version": "0.1.0",
		})
	})

	handlers.RegisterRoutes(r, client)

	// Swagger (doc API).
	docs.SwaggerInfo.BasePath = "/v1"
	r.GET("/swagger/*any", ginSwagger.WrapHandler(swaggerFiles.Handler))

	_ = r.Run(":" + port)
}
