package ipapi

import (
	"context"
	"log/slog"
	"testing"

	"git.eeqj.de/sneak/ipapi/internal/config"
	"git.eeqj.de/sneak/ipapi/internal/database"
	"git.eeqj.de/sneak/ipapi/internal/http"
	"git.eeqj.de/sneak/ipapi/internal/state"
	"github.com/go-chi/chi/v5"
)

func TestNew(t *testing.T) {
	cfg := &config.Config{
		Port:     8080,
		StateDir: t.TempDir(),
		LogLevel: "info",
	}
	logger := slog.Default()
	stateManager, _ := state.New(cfg, logger)
	dbManager, _ := database.New(cfg, logger, stateManager)
	router := chi.NewRouter()
	server, _ := http.NewServer(cfg, logger, router)

	opts := Options{
		Config:   cfg,
		Logger:   logger,
		State:    stateManager,
		Database: dbManager,
		Server:   server,
	}

	ipapi := New(opts)
	if ipapi == nil {
		t.Fatal("expected IPAPI instance, got nil")
	}

	if ipapi.config != cfg {
		t.Error("config not set correctly")
	}

	if ipapi.logger != logger {
		t.Error("logger not set correctly")
	}

	if ipapi.state != stateManager {
		t.Error("state manager not set correctly")
	}

	if ipapi.database != dbManager {
		t.Error("database manager not set correctly")
	}

	if ipapi.server != server {
		t.Error("server not set correctly")
	}
}

func TestStartStop(t *testing.T) {
	cfg := &config.Config{
		Port:     0, // Random port
		StateDir: t.TempDir(),
		LogLevel: "info",
	}
	logger := slog.Default()
	stateManager, _ := state.New(cfg, logger)
	dbManager, _ := database.New(cfg, logger, stateManager)
	router := chi.NewRouter()
	server, _ := http.NewServer(cfg, logger, router)

	opts := Options{
		Config:   cfg,
		Logger:   logger,
		State:    stateManager,
		Database: dbManager,
		Server:   server,
	}

	ipapi := New(opts)
	ctx := context.Background()

	// Initialize state first
	if err := stateManager.Initialize(ctx); err != nil {
		t.Fatalf("failed to initialize state: %v", err)
	}

	// Stop should work even if not started
	if err := ipapi.Stop(ctx); err != nil {
		t.Errorf("stop failed: %v", err)
	}
}
