package controllers

import (
	"log"
	"net/http"
	"strconv"
	"time"

	"github.com/gin-gonic/gin"
	"gitlab.com/pactual1/backend/database/notification"
)

func GetNotifications(c *gin.Context) {
	// Get the Company ID and Time from query parameters
	companyIDStr := c.DefaultQuery("company_id", "")
	timeStr := c.DefaultQuery("time", "")

	if companyIDStr == "" || timeStr == "" {
		log.Printf("GetNotifications Error: Company ID and Time are required")
		c.JSON(http.StatusBadRequest, gin.H{"error": "Company ID and Time are required"})
		return
	}

	// Convert string to int for UserID
	userID, err := strconv.Atoi(companyIDStr)
	if err != nil {
		log.Printf("GetNotifications Error: Invalid Company ID: %v", err)
		c.JSON(http.StatusBadRequest, gin.H{"error": "Invalid User ID"})
		return
	}

	timestamp, err := strconv.ParseInt(timeStr, 10, 64)
	if err != nil {
		log.Printf("GetNotifications Error: afterTime parameter ID: %v", err)
		c.JSON(http.StatusBadRequest, gin.H{"error": "After time parameter ID"})
		return
	}
	afterTime := time.Unix(timestamp, 0)

	log.Printf("This is the Company ID: %v and Time: %v", userID, afterTime)
	notifications, st, err := notification.GetNotificationsForCompanyID(userID, afterTime)

	if err != nil {
		c.JSON(st, gin.H{"error": err.Error()})
		return
	}

	// Respond with the notifications
	c.JSON(http.StatusOK, gin.H{"data": notifications})
}
