package main

import (
	"fmt"
	"log"
	"time"

	"github.com/nats-io/nats.go"
)

func main() {
	// Connect to NATS server
	nc, err := nats.Connect(nats.DefaultURL)
	if err != nil {
		log.Fatal("Failed to connect to NATS:", err)
	}
	defer nc.Close()

	// Get JetStream context
	js, err := nc.JetStream()
	if err != nil {
		log.Fatal("Failed to get JetStream context:", err)
	}

	// Check if the stream exists
	streamName := "SCRAPER_STREAM"
	streamInfo, err := js.StreamInfo(streamName)
	if err != nil {
		log.Fatal("Failed to get stream info:", err)
	}

	fmt.Printf("Stream: %s\n", streamInfo.Config.Name)
	fmt.Printf("Messages: %d\n", streamInfo.State.Msgs)
	fmt.Printf("Subjects: %v\n", streamInfo.Config.Subjects)
	fmt.Printf("Storage: %s\n", streamInfo.Config.Storage)
	fmt.Printf("Max Age: %s\n", streamInfo.Config.MaxAge)
	fmt.Println("---")

	if streamInfo.State.Msgs == 0 {
		fmt.Println("No messages found in the stream")
		return
	}

	// Subscribe to get messages
	sub, err := js.PullSubscribe("", "temp-checker", nats.BindStream(streamName))
	if err != nil {
		log.Fatal("Failed to create subscription:", err)
	}
	defer sub.Unsubscribe()

	fmt.Println("Messages in the stream:")
	fmt.Println("======================")

	// Fetch messages
	msgs, err := sub.Fetch(int(streamInfo.State.Msgs), nats.MaxWait(5*time.Second))
	if err != nil {
		log.Printf("Error fetching messages: %v", err)
		return
	}

	for i, msg := range msgs {
		fmt.Printf("Message %d:\n", i+1)
		fmt.Printf("  Subject: %s\n", msg.Subject)
		fmt.Printf("  Data: %s\n", string(msg.Data))

		// Get metadata
		metadata, err := msg.Metadata()
		if err == nil {
			fmt.Printf("  Timestamp: %s\n", time.Unix(0, metadata.Timestamp.UnixNano()).Format(time.RFC3339))
			fmt.Printf("  Sequence: %d\n", metadata.Sequence.Stream)
		}
		fmt.Println("  ---")

		// Acknowledge the message
		msg.Ack()
	}

	// Clean up the temporary consumer
	js.DeleteConsumer(streamName, "temp-checker")
}
