package main

import (
	"strconv"
	"whatsapp-bot/db"
	"whatsapp-bot/handlers"

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

func main() {
	godotenv.Load()
	db.Init()

	r := gin.Default()
	r.LoadHTMLGlob("templates/*")
	r.Static("/static", "./static") // Serve the CSS

	// PUBLIC ROUTES
	r.GET("/", handlers.ShowLanding)
	r.GET("/login", handlers.ShowLogin)
	r.POST("/login", handlers.LoginHandler)
	r.GET("/register", handlers.ShowRegister)
	r.POST("/register", handlers.RegisterHandler)
	r.GET("/logout", handlers.LogoutHandler)

	r.GET("/webhook", handlers.VerifyWebhook)
	r.POST("/webhook", handlers.HandleMessage)

	// PRIVATE ROUTES (Middleware)
	auth := r.Group("/")
	auth.Use(AuthMiddleware())
	{
		auth.GET("/dashboard", handlers.UserDashboard)
		auth.POST("/update-bot", handlers.UpdateBotSettings)
		auth.GET("/api/my-appointments", handlers.MyAppointmentsAPI)
		auth.POST("/admin/appointment/:id/cancel", handlers.CancelAppointmentHandler)
	}

	r.Run(":9090")
}

func AuthMiddleware() gin.HandlerFunc {
	return func(c *gin.Context) {
		cookie, err := c.Cookie("user_id")
		if err != nil {
			c.Redirect(302, "/login")
			c.Abort()
			return
		}
		// Convert cookie to Int
		uid, _ := strconv.Atoi(cookie)
		c.Set("userID", uid)
		c.Next()
	}
}
