package config

import (
	"testing"
	"time"
)

func TestTracearrURLAndKeyMustBeConfiguredTogether(t *testing.T) {
	t.Setenv("MEMBY_EMBY_URL", "http://emby")
	t.Setenv("MEMBY_DATABASE_URL", "postgres://memby")
	t.Setenv("MEMBY_TRACEARR_URL", "http://tracearr")
	t.Setenv("MEMBY_TRACEARR_API_KEY", "")

	if _, err := Load(); err == nil {
		t.Fatal("expected incomplete Tracearr configuration to fail")
	}
}

func TestRadarrURLAndKeyMustBeConfiguredTogether(t *testing.T) {
	t.Setenv("MEMBY_EMBY_URL", "http://emby")
	t.Setenv("MEMBY_DATABASE_URL", "postgres://memby")
	t.Setenv("MEMBY_RADARR_URL", "http://radarr")
	t.Setenv("MEMBY_RADARR_API_KEY", "")

	if _, err := Load(); err == nil {
		t.Fatal("expected incomplete Radarr configuration to fail")
	}
}

func TestForYouDefaultsToDailyOffPeakRebuild(t *testing.T) {
	t.Setenv("MEMBY_EMBY_URL", "http://emby")
	t.Setenv("MEMBY_DATABASE_URL", "postgres://memby")
	t.Setenv("MEMBY_FOR_YOU_MIN_REBUILD_AGE", "")
	t.Setenv("MEMBY_FOR_YOU_REFRESH_INTERVAL", "")
	t.Setenv("MEMBY_FOR_YOU_REBUILD_HOUR", "")

	cfg, err := Load()
	if err != nil {
		t.Fatal(err)
	}
	if cfg.ForYouMinRebuildAge != 24*time.Hour ||
		cfg.ForYouRefreshInterval != 24*time.Hour ||
		cfg.ForYouRebuildHour != 4 {
		t.Fatalf("For You schedule = %v/%v hour %d",
			cfg.ForYouMinRebuildAge, cfg.ForYouRefreshInterval, cfg.ForYouRebuildHour)
	}
}

func TestForYouRebuildHourIsValidated(t *testing.T) {
	t.Setenv("MEMBY_EMBY_URL", "http://emby")
	t.Setenv("MEMBY_DATABASE_URL", "postgres://memby")
	t.Setenv("MEMBY_FOR_YOU_REBUILD_HOUR", "24")
	if _, err := Load(); err == nil {
		t.Fatal("expected invalid rebuild hour to fail")
	}
}

func TestRecommendationWeightsMustBeJSON(t *testing.T) {
	t.Setenv("MEMBY_EMBY_URL", "http://emby")
	t.Setenv("MEMBY_DATABASE_URL", "postgres://memby")
	t.Setenv("MEMBY_RECOMMENDATION_WEIGHTS", "{broken")
	if _, err := Load(); err == nil {
		t.Fatal("expected invalid recommendation weights to fail")
	}
}
