package handlers

import (
	"log"
	"net/http"

	"abuse_registration_poc/internal/models"
	"abuse_registration_poc/internal/utils"
)

// Login mirrors the original API login handler shape: validate user credentials,
// generate a JWT, and return {message, token}.
func (h *Handler) Login(writer http.ResponseWriter, request *http.Request) {
	var user models.ValidateUser
	if err := DecodeJSON(request, &user); err != nil {
		log.Printf("Error parsing request data: %v", err)
		WriteJSON(writer, http.StatusBadRequest, map[string]string{"message": "Could not parse request data."})
		return
	}

	if err := h.users.ValidateCredentials(&user); err != nil {
		log.Printf("Error validating credentials: %v", err)
		WriteJSON(writer, http.StatusUnauthorized, map[string]string{"message": "Could not authenticate user."})
		return
	}

	token, err := utils.GenerateToken(user.UserName, user.ID, user.Role)
	if err != nil {
		log.Printf("Error generating token: %v", err)
		WriteJSON(writer, http.StatusInternalServerError, map[string]string{"message": "Could not authenticate user."})
		return
	}

	WriteJSON(writer, http.StatusOK, map[string]string{"message": "Login successful!", "token": token})
}
