package controller

import (
	"dashboard/models"
	"dashboard/pkg/jwt"
	"dashboard/utils"
	"fmt"
	"net/http"

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

func LoginPage(c *gin.Context) {
	log, _ := utils.GetLogFromContext(c)

	log.Info("Serving login page")

	c.File(models.FileLoginHtml)
}

func UserSignInHandler(jwtC *jwt.Jwt) func(c *gin.Context) error {
	return func(c *gin.Context) error {
		log, _ := utils.GetLogFromContext(c)

		var user models.UserInfoParams

		if err := c.ShouldBindJSON(&user); err != nil {
			return err
		}

		if user.Password != models.AdminPassword {
			return models.ErrorPasswordErr
		}

		tokenStr, err := jwtC.GenToken(map[string]interface{}{
			"username": "admin",
		})

		if err != nil {
			fmt.Println(err)
			return err
		}

		token := fmt.Sprintf("%s%s", models.GinAuthorPrefixKey, tokenStr)

		log.Sugar().Infof("Set token: %s", token)

		c.SetCookie(models.GinAuthorKey, token, 24*60*60, "/", "", false, true)

		c.JSON(http.StatusOK, gin.H{"message": "Login successful"})

		return nil
	}
}

func UserLogOutHandler(c *gin.Context) {
	log, _ := utils.GetLogFromContext(c)

	c.SetCookie(models.GinAuthorKey, "", -1, "/", "", false, true)

	log.Sugar().Info("Logout successful")
	
	c.JSON(http.StatusOK, gin.H{"message": "Logout successful"})
}
