package api

import (
	"context"
	"fmt"
	"net/http"
	"time"

	"github.com/gin-gonic/gin"

	"github.com/rycroftapparel/workpulse-api/internal/httpapi"
)

func (s *Server) streamNotifications(c *gin.Context) {
	uid := userID(c)
	fl, ok := c.Writer.(http.Flusher)
	if !ok {
		c.JSON(http.StatusInternalServerError, httpapi.Fail("sse", "streaming unsupported"))
		return
	}
	h := c.Writer.Header()
	h.Set("Content-Type", "text/event-stream")
	h.Set("Cache-Control", "no-cache")
	h.Set("Connection", "keep-alive")
	c.Status(http.StatusOK)
	fl.Flush()

	sendCount := func() {
		ctx, cancel := context.WithTimeout(context.Background(), s.Cfg.QueryTimeout)
		defer cancel()
		var n int
		_ = s.DB.QueryRowContext(ctx, `SELECT COUNT(*) FROM notifications WHERE user_id = $1 AND read_at IS NULL`, uid).Scan(&n)
		_, _ = fmt.Fprintf(c.Writer, "event: unread\ndata: %d\n\n", n)
		fl.Flush()
	}
	sendCount()

	t := time.NewTicker(20 * time.Second)
	defer t.Stop()
	for {
		select {
		case <-c.Request.Context().Done():
			return
		case <-t.C:
			_, _ = fmt.Fprintf(c.Writer, ": ping\n\n")
			fl.Flush()
			sendCount()
		}
	}
}
