package config

import (
	"testing"
	"time"
)

func TestLoadDefaults(t *testing.T) {
	t.Setenv("SEEN_HTTP_PORT", "invalid")
	t.Setenv("SEEN_HTTP_READ_TIMEOUT", "invalid")

	cfg := Load()

	if cfg.HTTP.Port != 8081 {
		t.Fatalf("expected default port 8081, got %d", cfg.HTTP.Port)
	}

	if cfg.HTTP.ReadTimeout != 15*time.Second {
		t.Fatalf("expected default read timeout, got %s", cfg.HTTP.ReadTimeout)
	}
}

func TestLoadCustomValues(t *testing.T) {
	t.Setenv("SEEN_ENV", "test")
	t.Setenv("SEEN_HTTP_PORT", "9090")
	t.Setenv("SEEN_HTTP_READ_TIMEOUT", "5s")
	t.Setenv("SEEN_POSTGRES_MAX_CONNS", "22")
	t.Setenv("SEEN_CACHE_DB", "3")
	t.Setenv("SEEN_IGDB_CLIENT_ID", "client-id")
	t.Setenv("SEEN_IGDB_TOKEN_URL", "https://id.twitch.tv/oauth2/token")
	t.Setenv("SEEN_CORS_ALLOWED_ORIGINS", "https://seen.example.com, https://www.seen.example.com")
	t.Setenv("SEEN_CORS_ALLOW_CREDENTIALS", "true")

	cfg := Load()

	if cfg.Env != "test" {
		t.Fatalf("expected env test, got %q", cfg.Env)
	}

	if cfg.HTTP.Port != 9090 {
		t.Fatalf("expected http port 9090, got %d", cfg.HTTP.Port)
	}

	if cfg.HTTP.ReadTimeout != 5*time.Second {
		t.Fatalf("expected read timeout 5s, got %s", cfg.HTTP.ReadTimeout)
	}

	if cfg.Postgres.MaxConns != 22 {
		t.Fatalf("expected max conns 22, got %d", cfg.Postgres.MaxConns)
	}

	if cfg.Cache.DB != 3 {
		t.Fatalf("expected cache db 3, got %d", cfg.Cache.DB)
	}

	if cfg.IGDB.ClientID != "client-id" {
		t.Fatalf("expected igdb client id to load, got %q", cfg.IGDB.ClientID)
	}

	if cfg.IGDB.TokenURL != "https://id.twitch.tv/oauth2/token" {
		t.Fatalf("expected igdb token url to load, got %q", cfg.IGDB.TokenURL)
	}

	if len(cfg.CORS.AllowedOrigins) != 2 {
		t.Fatalf("expected 2 cors origins, got %d", len(cfg.CORS.AllowedOrigins))
	}

	if !cfg.CORS.AllowCredentials {
		t.Fatal("expected allow credentials to be true")
	}
}
