package handlers

import (
	"net/http"
	"os"
	"time"

	"github.com/gin-gonic/gin"
	"github.com/golang-jwt/jwt/v5"
	"golang.org/x/crypto/bcrypt"

	"viplight-mrp/database"
	"viplight-mrp/models"
)

func Login(c *gin.Context) {
	jwtKey := []byte(os.Getenv("JWT_SECRET"))
	var input struct {
		Username string `json:"username"`
		Password string `json:"password"`
	}

	if err := c.ShouldBindJSON(&input); err != nil {
		c.JSON(http.StatusBadRequest, gin.H{"error": "Invalid input"})
		return
	}

	var user models.User

	err := database.DB.Where("username = ?", input.Username).First(&user).Error

	passErr := bcrypt.CompareHashAndPassword([]byte(user.Password), []byte(input.Password))

	if err != nil || passErr != nil {
		c.JSON(http.StatusUnauthorized, gin.H{"error": "Invalid login or password"})
		return
	}

	token := jwt.NewWithClaims(jwt.SigningMethodHS256, jwt.MapClaims{
		"user_id": user.ID,
		"role":    user.Role,
		"exp":     time.Now().Add(time.Hour * 24).Unix(),
	})

	tokenString, _ := token.SignedString(jwtKey)

	c.JSON(http.StatusOK, gin.H{"token": tokenString})
}

func Register(c *gin.Context) {
	var input struct {
		Username string `json:"username" binding:"required"`
		Password string `json:"password" binding:"required"`
	}

	// 1. Проверяем входящие данные
	if err := c.ShouldBindJSON(&input); err != nil {
		c.JSON(http.StatusBadRequest, gin.H{"error": "Invalid input"})
		return
	}

	// 2. Хешируем пароль (чтобы не хранить его в открытом виде)
	hashedPassword, err := bcrypt.GenerateFromPassword([]byte(input.Password), bcrypt.DefaultCost)
	if err != nil {
		c.JSON(http.StatusInternalServerError, gin.H{"error": "Failed to hash password"})
		return
	}

	// 3. Создаем объект пользователя
	user := models.User{
		Username: input.Username,
		Password: string(hashedPassword),
		Role:     "user", // по умолчанию
	}

	// 4. Сохраняем в базу через GORM
	if err := database.DB.Create(&user).Error; err != nil {
		c.JSON(http.StatusInternalServerError, gin.H{"error": "Could not create user maybe username exists?"})
		return
	}
	c.JSON(http.StatusOK, gin.H{"message": "Registration successful"})
}
