package main

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

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

//go:embed docs/openapi.json
var swaggerJSON string

func withCORS(handler http.Handler) http.Handler {
	return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
		w.Header().Set("Access-Control-Allow-Origin", "*")
		w.Header().Set("Access-Control-Allow-Methods", "GET, POST, OPTIONS")
		w.Header().Set("Access-Control-Allow-Headers", "Content-Type, Authorization")

		if r.Method == http.MethodOptions {
			w.WriteHeader(http.StatusNoContent)
			return
		}

		handler.ServeHTTP(w, r)
	})
}

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

	mux := http.NewServeMux()

	mux.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
		}

		mode := r.URL.Query().Get("mode")
		result, err := seeder.Seed(dsn, mode)
		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))
	})

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

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

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