package client

import (
	"fmt"
	"time"

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

// Connect establishes a connection to NATS with token authentication
// and automatic reconnection handling
func Connect(url, token string) (*nats.Conn, error) {
	opts := []nats.Option{
		nats.Token(token),
		nats.Name("corrosion-companion"),
		nats.MaxReconnects(-1), // Unlimited reconnect attempts
		nats.ReconnectWait(2 * time.Second),
		nats.DisconnectErrHandler(func(nc *nats.Conn, err error) {
			if err != nil {
				fmt.Printf("NATS disconnected: %v\n", err)
			}
		}),
		nats.ReconnectHandler(func(nc *nats.Conn) {
			fmt.Printf("NATS reconnected to %s\n", nc.ConnectedUrl())
		}),
		nats.ClosedHandler(func(nc *nats.Conn) {
			fmt.Println("NATS connection closed")
		}),
		nats.ErrorHandler(func(nc *nats.Conn, sub *nats.Subscription, err error) {
			fmt.Printf("NATS error: %v\n", err)
		}),
	}

	nc, err := nats.Connect(url, opts...)
	if err != nil {
		return nil, fmt.Errorf("failed to connect to NATS: %w", err)
	}

	return nc, nil
}
