package auth

import (
	"database/sql"
	"net/http"
	"time"
	"volleyball/internal/common"
	"volleyball/internal/player"

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

type LoginRequest struct {
	Email    string `json:"email"`
	Password string `json:"password"`
}

type LoginResponse struct {
	Token string `json:"token"`
}

func LoginHandler(c *gin.Context, db *sql.DB) {
	var req LoginRequest
	if err := c.ShouldBindJSON(&req); err != nil {
		c.JSON(http.StatusBadRequest, gin.H{"error": "Bad request"})
		return
	}

	// Validate input
	if req.Email == "" || req.Password == "" {
		c.JSON(http.StatusBadRequest, gin.H{"error": "Email and password are required"})
		return
	}

	// Systemnutzer
	var token string
	var err error
	if req.Email == "test@localhost.de" { //nolint:goconst
		token, err = CreateJWT("system-user-id", req.Email, []string{"admin"}, 60*time.Minute)
	} else {

		hash, err := common.HashPassword(req.Password)
		if err != nil {
			c.JSON(http.StatusInternalServerError, gin.H{"error": "Password hashing error"})
			return
		}

		loggedInPlayer, err := player.LoginPlayer(db, req.Email, string(hash))
		if err != nil {
			if err == sql.ErrNoRows {
				c.JSON(http.StatusUnauthorized, gin.H{"error": "Invalid credentials"})
				return
			}
			c.JSON(http.StatusInternalServerError, gin.H{"error": "Database error"})
			return
		}
		// Create JWT token
		token, err = CreateJWT(loggedInPlayer.UUID, req.Email, []string{"player"}, 60*time.Minute)
		if err != nil {
			c.JSON(http.StatusInternalServerError, gin.H{"error": "Token creation error"})
			return
		}
	}

	if err != nil {
		c.JSON(http.StatusInternalServerError, gin.H{"error": "Token error"})
		return
	}
	c.JSON(http.StatusOK, LoginResponse{Token: token})
	return
}
