package main

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

	"github.com/joho/godotenv"
	"github.com/saveinmed/seeder-api/pkg/seeder"
)

func main() {
	godotenv.Load()
	port := os.Getenv("PORT")
	if port == "" {
		port = "8080"
	}

	http.HandleFunc("/seed", func(w http.ResponseWriter, r *http.Request) {
		if r.Method != http.MethodPost {
			http.Error(w, "Method not allowed", http.StatusMethodNotAllowed)
			return
		}

		dsn := os.Getenv("DATABASE_URL")
		if dsn == "" {
			http.Error(w, "DATABASE_URL not set", http.StatusInternalServerError)
			return
		}

		result, err := seeder.Seed(dsn)
		if err != nil {
			log.Printf("Seeder error: %v", err)
			http.Error(w, err.Error(), http.StatusInternalServerError)
			return
		}

		w.Header().Set("Content-Type", "application/json")
		w.Write([]byte(result))
	})

	log.Printf("Seeder API listening on port %s", port)
	if err := http.ListenAndServe(":"+port, nil); err != nil {
		log.Fatalf("Server error: %v", err)
	}
}
