package main

import (
	"context"
	"log/slog"
	"net/http"
	"os"
	"path/filepath"

	"git.toki-labs.com/toki/gito/services/core/internal/config"
	"git.toki-labs.com/toki/gito/services/core/internal/controlplane"
	"git.toki-labs.com/toki/gito/services/core/internal/storage"
)

// migrationSQL loads the initial migration SQL from well-known paths relative
// to the executable or common working directories, so the server works
// regardless of the cwd it is launched from.
func migrationSQL() string {
	exe, err := os.Executable()
	if err != nil {
		exe = ""
	}
	candidates := []string{
		// set explicitly via env
		os.Getenv("GITO_MIGRATION_PATH"),
		// next to the binary (bin/gito-server → bin/../migrations/...)
		filepath.Join(filepath.Dir(exe), "migrations", "00001_initial.sql"),
		// launched from repo root
		filepath.Join("services", "core", "migrations", "00001_initial.sql"),
		// launched from services/core
		filepath.Join("migrations", "00001_initial.sql"),
	}
	for _, p := range candidates {
		if p == "" {
			continue
		}
		data, err := os.ReadFile(p)
		if err == nil {
			return string(data)
		}
	}
	return ""
}

func main() {
	cfg := config.Load()
	logger := slog.New(slog.NewJSONHandler(os.Stdout, nil))

	var pgStore *storage.PgStore
	if dsn := os.Getenv("DATABASE_URL"); dsn != "" {
		var err error
		pgStore, err = storage.NewPgStore(context.Background(), dsn, migrationSQL())
		if err != nil {
			logger.Error("failed to open postgres store", "error", err)
			os.Exit(1)
		}
		logger.Info("postgres store connected")
	}

	var handler http.Handler
	if pgStore != nil {
		handler = controlplane.NewRouterWithStore(cfg, logger, pgStore)
	} else {
		handler = controlplane.NewRouter(cfg, logger)
	}

	if pgStore != nil {
		defer pgStore.Close()
	}

	server := &http.Server{
		Addr:    cfg.HTTPAddr,
		Handler: handler,
	}

	logger.Info("gito control plane listening", "addr", cfg.HTTPAddr)
	if err := server.ListenAndServe(); err != nil && err != http.ErrServerClosed {
		logger.Error("server stopped", "error", err)
		os.Exit(1)
	}
}
