package main

import (
	"log"
	"os"

	"github.com/gin-gonic/gin"
	"gorm.io/driver/postgres"
	"gorm.io/driver/sqlite"
	"gorm.io/gorm"
)

// ===================== Globals =====================

var (
	db           *gorm.DB
	baseURL      string
	cookieDomain string
)

const (
	PORT = "18765"
)

var logger = log.Default()

// ===================== Main =====================

func main() {
	log.SetFlags(log.LstdFlags | log.Lshortfile)

	baseURL = os.Getenv("APP_BASE_URL")
	if baseURL == "" {
		baseURL = "http://localhost:" + PORT
	}
	cookieDomain = os.Getenv("APP_COOKIE_DOMAIN")

	// DB connect
	var err error
	dsn := os.Getenv("DATABASE_URL")
	if dsn != "" {
		db, err = gorm.Open(postgres.Open(dsn), &gorm.Config{})
		if err != nil {
			log.Fatal("postgres connect:", err)
		}
		log.Println("using Postgres")
	} else {
		db, err = gorm.Open(sqlite.Open("qrank.db"), &gorm.Config{})
		if err != nil {
			log.Fatal("sqlite connect:", err)
		}
		log.Println("using SQLite qrank.db")
	}

	if err := db.AutoMigrate(&User{}, &Session{}, &LoginToken{}, &Table{}, &Game{}, &GamePlayer{}); err != nil {
		log.Fatal("migrate:", err)
	}

	r := gin.Default()

	// Serve static files from the current directory
	r.Static("/assets", "./assets")

	// Routes
	r.GET("/", getIndex)
	r.GET("/login", getLogin)
	r.POST("/login", postLogin)
	r.GET("/magic", getMagic)

	// Authenticated routes
	r.GET("/enter", requireAuth(), getEnter)
	r.POST("/enter", requireAuth(), postEnter)

	// QR-prepped table routes
	r.GET("/t/:tslug/enter", requireAuth(), getEnter)
	r.POST("/t/:tslug/enter", requireAuth(), postEnter)

	r.GET("/history", requireAuth(), getHistory)
	r.GET("/leaderboard", requireAuth(), getLeaderboard)

	r.GET("/u/:slug", requireAuth(), getUserView)
	r.GET("/me", requireAuth(), getMe)
	r.POST("/me", requireAuth(), postMe)

	bind := os.Getenv("APP_BIND")
	if bind == "" {
		bind = ":" + PORT
	}
	log.Println("listening on", bind, "base:", baseURL)
	if err := r.Run(bind); err != nil {
		log.Fatal(err)
	}
}
