package notification

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

	"github.com/jinzhu/gorm"
	"gitlab.com/pactual1/backend/models"
	"gitlab.com/pactual1/backend/shared"
)


func GetNotificationsForCompanyID(companyID int, afterTime time.Time) ([]models.GetNotificationsResponse, int, error) {
	// Create a slice to hold the notifications
	var notifications []models.Notification
	var customNotifications []models.GetNotificationsResponse

	// Fetch notifications from the database based on UserID and creation time
	if err := shared.GetDb().Where("company_id = ? AND created_at > ?", companyID, afterTime).Find(&notifications).Error; err != nil {
		if errors.Is(err, gorm.ErrRecordNotFound) {
			log.Printf("GetNotificationsForCompanyID Error: No notifications found: %v", err)
			return customNotifications, http.StatusNotFound, err
		} else {
			log.Printf("GetNotificationsForCompanyID Error: Database error: %v", err)
			return customNotifications, http.StatusInternalServerError, err
		}
	}

	// Transform to custom response format
	for _, n := range notifications {
		customNotification := models.GetNotificationsResponse{
			Type:     n.NotificationType,
			Title:    n.Title,
			Message:  n.Text,
			DateTime: n.CreatedAt,
		}
		customNotifications = append(customNotifications, customNotification)
	}

	return customNotifications, http.StatusOK, nil

}