package utils

import (
	"bytes"
	"encoding/json"
	"net/http"
	"os"
)

type TrackingEvent struct {
	APIKey     string `json:"api_key"`
	SiteID     string `json:"site_id"`
	Type       string `json:"type"`
	Pathname   string `json:"pathname"`
	Hostname   string `json:"hostname,omitempty"`
	EventName  string `json:"event_name,omitempty"`
	Properties string `json:"properties,omitempty"`
}

func trackEvent(event TrackingEvent) error {
	event.APIKey = os.Getenv("RYBBIT_API_KEY")
	event.SiteID = os.Getenv("RYBBIT_SITE_ID")

	if event.APIKey == "" {
		return nil // Skip if no API key configured
	}

	jsonData, err := json.Marshal(event)
	if err != nil {
		return err
	}

	resp, err := http.Post(
		"https://a.adhd.sh/api/track",
		"application/json",
		bytes.NewBuffer(jsonData),
	)
	if err != nil {
		return err
	}
	defer resp.Body.Close()

	return nil
}

func SendAnalyticsEvent(eventType, pathname string) error {
	return trackEvent(TrackingEvent{
		Type:     eventType,
		Pathname: pathname,
	})
}

func SendCustomEvent(eventName, pathname, properties string) error {
	return trackEvent(TrackingEvent{
		Type:       "custom_event",
		Pathname:   pathname,
		EventName:  eventName,
		Properties: properties,
	})
}
