package main

import (
	"log"
	"net/http"
	"os"

	"github.com/elastic/go-elasticsearch/v8"
	"github.com/explorer/backend/api/search"
	"github.com/explorer/backend/search/config"
)

func main() {
	searchConfig := config.LoadSearchConfig()

	esConfig := elasticsearch.Config{
		Addresses: []string{searchConfig.URL},
	}

	if searchConfig.Username != "" {
		esConfig.Username = searchConfig.Username
		esConfig.Password = searchConfig.Password
	}

	client, err := elasticsearch.NewClient(esConfig)
	if err != nil {
		log.Fatalf("Failed to create Elasticsearch client: %v", err)
	}

	service := search.NewSearchService(client, searchConfig.IndexPrefix)

	mux := http.NewServeMux()
	mux.HandleFunc("/api/v1/search", service.HandleSearch)

	port := os.Getenv("SEARCH_PORT")
	if port == "" {
		port = "8082"
	}

	log.Printf("Starting search service on :%s", port)
	log.Fatal(http.ListenAndServe(":"+port, mux))
}
