package handlers

import (
	"net/http"
	"strconv"

	"veza-backend-api/internal/services"

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

var NotificationHandlersInstance *NotificationHandlers

type NotificationHandlers struct {
	notificationService *services.NotificationService
}

func NewNotificationHandlers(notificationService *services.NotificationService) {
	NotificationHandlersInstance = &NotificationHandlers{
		notificationService: notificationService,
	}
}

// GetNotifications retrieves all notifications for the authenticated user
func (nh *NotificationHandlers) GetNotifications(c *gin.Context) {
	userID, exists := c.Get("user_id")
	if !exists {
		c.JSON(http.StatusUnauthorized, gin.H{"error": "User not authenticated"})
		return
	}

	read := c.DefaultQuery("read", "")
	var unreadOnly bool
	if read == "false" {
		unreadOnly = true
	}

	notifications, err := nh.notificationService.GetNotifications(int64(userID.(int)), unreadOnly)
	if err != nil {
		c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
		return
	}

	c.JSON(http.StatusOK, notifications)
}

// MarkAsRead marks a notification as read
func (nh *NotificationHandlers) MarkAsRead(c *gin.Context) {
	userID, exists := c.Get("user_id")
	if !exists {
		c.JSON(http.StatusUnauthorized, gin.H{"error": "User not authenticated"})
		return
	}

	notificationID, err := strconv.ParseInt(c.Param("id"), 10, 64)
	if err != nil {
		c.JSON(http.StatusBadRequest, gin.H{"error": "Invalid notification ID"})
		return
	}

	err = nh.notificationService.MarkAsRead(int64(userID.(int)), notificationID)
	if err != nil {
		c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
		return
	}

	c.JSON(http.StatusOK, gin.H{"message": "Notification marked as read"})
}

// MarkAllAsRead marks all notifications as read for the user
func (nh *NotificationHandlers) MarkAllAsRead(c *gin.Context) {
	userID, exists := c.Get("user_id")
	if !exists {
		c.JSON(http.StatusUnauthorized, gin.H{"error": "User not authenticated"})
		return
	}

	err := nh.notificationService.MarkAllAsRead(int64(userID.(int)))
	if err != nil {
		c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
		return
	}

	c.JSON(http.StatusOK, gin.H{"message": "All notifications marked as read"})
}

// GetUnreadCount returns the count of unread notifications
func (nh *NotificationHandlers) GetUnreadCount(c *gin.Context) {
	userID, exists := c.Get("user_id")
	if !exists {
		c.JSON(http.StatusUnauthorized, gin.H{"error": "User not authenticated"})
		return
	}

	count, err := nh.notificationService.GetUnreadCount(int64(userID.(int)))
	if err != nil {
		c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
		return
	}

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