package authentication

import (
	"database/sql"
	"net/http"

	"github.com/gin-gonic/gin"
	"spahl.ddns.net/jasper/wok-able-backend/auth"
	"spahl.ddns.net/jasper/wok-able-backend/models"
)

func Register(c *gin.Context) {
	var user models.User
	if err := c.BindJSON(&user); err != nil || user.Email == "" || user.Username == "" {
		c.Status(http.StatusBadRequest)
		return
	}
	if err := models.DB.Create(&user).Save(&user).Error; err != nil {
		c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
		return
	}
	token, err := auth.GenerateJWT(user.ID, user.Username, user.Email)
	if err != nil {
		c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
		return
	}
	c.SetCookie("token", token, 2*60*60, "", "", false, true)
	c.JSON(http.StatusCreated, gin.H{"username": user.Username, "email": user.Email})
}

func Login(c *gin.Context) {
	var authentication models.Auth
	if err := c.BindJSON(&authentication); err != nil {
		c.Status(http.StatusBadRequest)
		return
	}
	var user models.User
	models.DB.Where("username = @name OR email = @name", sql.Named("name", authentication.Username)).First(&user)
	if user.Email == "" {
		c.JSON(http.StatusUnauthorized, gin.H{"error": "Username or Password is incorrect"})
		return
	}

	if err := auth.CheckPassword(authentication.Password, user.Salt, user.PasswordHash); err != nil {
		c.JSON(http.StatusUnauthorized, gin.H{"error": "Username or Password is incorrect"})
		return
	}

	token, _ := auth.GenerateJWT(user.ID, user.Username, user.Email)
	c.SetCookie("token", token, 2*60*60, "", "", false, true)
	c.JSON(http.StatusOK, gin.H{"username": user.Username, "email": user.Email})
}

func Verify(c *gin.Context) {
	tokenCookie, err := c.Cookie("token")
	if err != nil || tokenCookie == "" {
		c.JSON(http.StatusUnauthorized, gin.H{"error": "Unauthorized"})
		return
	}
	claims, err := auth.VerifyJWT(tokenCookie)
	if err != nil {
		c.JSON(http.StatusUnauthorized, gin.H{"error": "Unauthorized"})
		return
	}
	c.JSON(http.StatusOK, gin.H{"username": claims["username"], "email": claims["email"]})
}

func Logout(c *gin.Context) {
	c.SetCookie("token", "", -1, "", "", false, true)
	c.Status(http.StatusOK)
}
