package integration_test

import (
	"context"
	"testing"

	"sub2api-cn-relay-manager/internal/app"
	"sub2api-cn-relay-manager/internal/config"
)

func TestLoadStartupFromEnvUsesDefaultsWhenOptionalValuesMissing(t *testing.T) {
	t.Setenv("SUB2API_CRM_LISTEN_ADDR", "")
	t.Setenv("SUB2API_CRM_SQLITE_DSN", "")

	cfg, err := config.LoadStartupFromEnv()
	if err != nil {
		t.Fatalf("LoadStartupFromEnv() returned error: %v", err)
	}

	if cfg.Server.ListenAddr != config.DefaultListenAddr {
		t.Fatalf("ListenAddr = %q, want %q", cfg.Server.ListenAddr, config.DefaultListenAddr)
	}

	if cfg.Database.SQLiteDSN != config.DefaultSQLiteDSN {
		t.Fatalf("SQLiteDSN = %q, want %q", cfg.Database.SQLiteDSN, config.DefaultSQLiteDSN)
	}
}

func TestLoadStartupFromEnvAppliesOverrides(t *testing.T) {
	t.Setenv("SUB2API_CRM_LISTEN_ADDR", "127.0.0.1:9090")
	t.Setenv("SUB2API_CRM_SQLITE_DSN", "file:custom.db?_foreign_keys=on")
	t.Setenv("SUB2API_CRM_REPO_ROOT", "/srv/sub2api-cn-relay-manager")

	cfg, err := config.LoadStartupFromEnv()
	if err != nil {
		t.Fatalf("LoadStartupFromEnv() returned error: %v", err)
	}

	if cfg.Server.ListenAddr != "127.0.0.1:9090" {
		t.Fatalf("ListenAddr = %q, want %q", cfg.Server.ListenAddr, "127.0.0.1:9090")
	}

	if cfg.Database.SQLiteDSN != "file:custom.db?_foreign_keys=on" {
		t.Fatalf("SQLiteDSN = %q, want %q", cfg.Database.SQLiteDSN, "file:custom.db?_foreign_keys=on")
	}

	if cfg.Repository.RepoRoot != "/srv/sub2api-cn-relay-manager" {
		t.Fatalf("RepoRoot = %q, want %q", cfg.Repository.RepoRoot, "/srv/sub2api-cn-relay-manager")
	}
}

func TestLoadAdminTokenFromEnvReturnsToken(t *testing.T) {
	t.Setenv("SUB2API_CRM_ADMIN_TOKEN", "admin-token")

	token, err := config.LoadAdminTokenFromEnv()
	if err != nil {
		t.Fatalf("LoadAdminTokenFromEnv() returned error: %v", err)
	}

	if token != "admin-token" {
		t.Fatalf("token = %q, want %q", token, "admin-token")
	}
}

func TestLoadAdminTokenFromEnvReturnsErrorWhenMissing(t *testing.T) {
	t.Setenv("SUB2API_CRM_ADMIN_TOKEN", "")

	_, err := config.LoadAdminTokenFromEnv()
	if err == nil {
		t.Fatal("LoadAdminTokenFromEnv() error = nil, want validation error")
	}
}

func TestBootstrapBuildsServerWithStartupConfigAndAdminToken(t *testing.T) {
	t.Setenv("SUB2API_CRM_LISTEN_ADDR", ":8181")
	t.Setenv("SUB2API_CRM_ADMIN_TOKEN", "admin-token")

	server, err := app.Bootstrap(context.Background())
	if err != nil {
		t.Fatalf("Bootstrap() returned error: %v", err)
	}

	if server == nil {
		t.Fatal("Bootstrap() returned nil server")
	}

	if server.Addr() != ":8181" {
		t.Fatalf("Bootstrap Addr = %q, want %q", server.Addr(), ":8181")
	}
}
