package controllers

import (
	"canguidev/shelfy/internal/models"
	"fmt"
	"net/http"
	"time"

	"github.com/gin-gonic/gin"
	"github.com/golang-jwt/jwt"
	"golang.org/x/crypto/bcrypt"
	"gorm.io/gorm"
)

func Login(db *gorm.DB) gin.HandlerFunc {
    return func(c *gin.Context) {
	var authInput models.User
	var user =models.User{}
	if err := c.ShouldBindJSON(&authInput); err != nil {
		c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
		return
	}

	

		d :=db.Where("Email = ?", authInput.Email).First(&user)
		if d.Error != nil {
			fmt.Println("Erreur lors de la requête :", d.Error)
		} else {
			// Afficher les données récupérées
			fmt.Printf("Utilisateur trouvé : %+v\n", user)
		}


		if err := bcrypt.CompareHashAndPassword([]byte(user.Password), []byte(authInput.Password)); err != nil {
			c.JSON(http.StatusBadRequest, gin.H{"error": "failed to generate token"})
		//	w.WriteHeader(http.StatusUnauthorized)
			return
		}

		generateToken := jwt.NewWithClaims(jwt.SigningMethodHS256, jwt.MapClaims{
			"id":  user.ID,
			"exp": time.Now().Add(time.Hour * 24).Unix(),
		})

	token, err := generateToken.SignedString([]byte("SECRET"))

	if err != nil {
		c.JSON(http.StatusBadRequest, gin.H{"error": "failed to generate token"})
	}

	c.JSON(200, gin.H{
		"token": token,
	})
}}