package config

import (
	"flag"
	"os"
	"testing"

	"gitea.miguelmuniz.com/rogueking/junk2jive-server/internal/router"
)

func TestDeclareFlags(t *testing.T) {
	// Save original command line arguments
	oldArgs := os.Args
	defer func() { os.Args = oldArgs }()

	// Set up test cases
	tests := []struct {
		name     string
		args     []string
		expected *Flags
	}{
		{
			name:     "No arguments",
			args:     []string{"cmd"},
			expected: &Flags{Port: 0},
		},
		{
			name:     "Port flag provided",
			args:     []string{"cmd", "-p", "8080"},
			expected: &Flags{Port: 8080},
		},
	}

	for _, tc := range tests {
		t.Run(tc.name, func(t *testing.T) {
			// Reset flags for each test
			flag.CommandLine = flag.NewFlagSet(tc.args[0], flag.ExitOnError)

			// Set the arguments
			os.Args = tc.args

			// Run the function
			got := DeclareFlags()

			// Check results
			if got.Port != tc.expected.Port {
				t.Errorf("DeclareFlags() Port = %v, want %v", got.Port, tc.expected.Port)
			}
		})
	}
}

func TestConfigPort(t *testing.T) {
	// Save original env and restore after test
	oldPort := os.Getenv("APP_PORT")
	defer os.Setenv("APP_PORT", oldPort)

	tests := []struct {
		name     string
		flags    *Flags
		envPort  string
		expected string
	}{
		{
			name:     "Flag port specified",
			flags:    &Flags{Port: 8080},
			envPort:  "9000",
			expected: ":8080",
		},
		{
			name:     "No flag port but env port specified",
			flags:    &Flags{Port: 0},
			envPort:  "9000",
			expected: ":9000",
		},
		{
			name:     "No ports specified - default to 80",
			flags:    &Flags{Port: 0},
			envPort:  "",
			expected: ":80",
		},
	}

	for _, tc := range tests {
		t.Run(tc.name, func(t *testing.T) {
			os.Setenv("APP_PORT", tc.envPort)

			got := ConfigPort(tc.flags)

			if got != tc.expected {
				t.Errorf("ConfigPort() = %v, want %v", got, tc.expected)
			}
		})
	}
}

func TestSetupServer(t *testing.T) {
	// Create mock router
	r := &router.Router{}
	flags := &Flags{Port: 8080}
	port := ":8080"

	server := SetupServer(port, r, flags)

	// Verify server was created with correct attributes
	if server == nil {
		t.Fatal("SetupServer() returned nil")
	}

	if server.Addr != port {
		t.Errorf("SetupServer() created server with Addr = %v, want %v", server.Addr, port)
	}
}

func TestLoadEnv(t *testing.T) {
	// Create a temporary .env file for testing
	tempEnvFile := "test.env"
	content := []byte("TEST_VAR=test_value\n")

	err := os.WriteFile(tempEnvFile, content, 0644)
	if err != nil {
		t.Fatalf("Failed to create test env file: %v", err)
	}
	defer os.Remove(tempEnvFile)

	// Test loading the file (this will fail if it can't load)
	// Since LoadEnv calls logger.Fatal on error, we can't easily test the failure case
	LoadEnv(tempEnvFile)

	// Verify the environment variable was loaded
	if os.Getenv("TEST_VAR") != "test_value" {
		t.Errorf("LoadEnv() didn't properly load TEST_VAR, got %v, want %v",
			os.Getenv("TEST_VAR"), "test_value")
	}
}
