package main

import (
	"context"
	"fmt"
	"time"

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

func main() {
	// Connect to NATS
	nc, err := nats.Connect(nats.DefaultURL)
	if err != nil {
		panic(err)
	}
	defer nc.Close()

	// Create JetStream context
	js, err := jetstream.New(nc)
	if err != nil {
		panic(err)
	}

	ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
	defer cancel()

	// Create object store
	testBucketName := fmt.Sprintf("test-bucket-%d", time.Now().UnixNano())
	obs, err := js.CreateObjectStore(ctx, jetstream.ObjectStoreConfig{
		Bucket: testBucketName,
	})
	if err != nil {
		panic(err)
	}
	fmt.Printf("Created bucket: %s\n", testBucketName)

	testJson := `{"test": "data"}`

	// 1. Delete non-existent object
	fmt.Println("\n1. Delete non-existent object testDelete.json:")
	err = obs.Delete(ctx, "testDelete.json")
	if err != nil {
		fmt.Printf("   Error (expected): %v\n", err)
	} else {
		fmt.Println("   No error (object was deleted or already gone)")
	}

	// 2. Get after delete - should fail
	fmt.Println("\n2. Get testDelete.json after delete:")
	_, err = obs.GetString(ctx, "testDelete.json")
	if err != nil {
		fmt.Printf("   Error (expected): %v\n", err)
	}

	// 3. Put string
	fmt.Println("\n3. Put testDelete.json:")
	info, err := obs.PutString(ctx, "testDelete.json", testJson)
	if err != nil {
		panic(err)
	}
	fmt.Printf("   Put successful, nuid: %s, chunks: %d, size: %d\n", info.NUID, info.Chunks, info.Size)

	// 4. First get after put - should work
	fmt.Println("\n4. First get testDelete.json after put:")
	result, err := obs.GetString(ctx, "testDelete.json")
	if err != nil {
		fmt.Printf("   Error: %v\n", err)
	} else {
		fmt.Printf("   Success: %s\n", result)
	}

	// 5. Second get - should also work
	fmt.Println("\n5. Second get testDelete.json (same operation as first get)::")
	result2, err := obs.GetString(ctx, "testDelete.json")
	if err != nil {
		fmt.Printf("   Error: %v\n", err)
	} else {
		fmt.Printf("   Success: %s\n", result2)
	}

	// 6. Test multiple gets in a loop
	fmt.Println("\n6. Test multiple gets in a loop:")
	for i := 1; i <= 5; i++ {
		_, err := obs.GetString(ctx, "testDelete.json")
		if err != nil {
			fmt.Printf("   Iteration %d: Error - %v\n", i, err)
			break
		} else {
			fmt.Printf("   Iteration %d: Success\n", i)
		}
	}

	// Cleanup
	js.DeleteObjectStore(ctx, testBucketName)
	fmt.Printf("\nBucket %s deleted\n", testBucketName)
}
