package main

import (
	"bytes"
	"encoding/json"
	"net/http"
	"net/http/httptest"
	"testing"

	"github.com/stretchr/testify/assert"
	"github.com/stretchr/testify/require"
)

// TestSystemSettingsHandler tests the system-wide scan settings endpoints
func TestSystemSettingsHandler(t *testing.T) {
	setup := setupTestServer(t)

	t.Run("GET /api/libraries/scan-settings - Get settings without auth", func(t *testing.T) {
		req := httptest.NewRequest("GET", "/api/libraries/scan-settings", nil)
		rec := httptest.NewRecorder()

		setup.Server.Config.Handler.ServeHTTP(rec, req)
		assert.Equal(t, http.StatusUnauthorized, rec.Code)
	})

	t.Run("GET /api/libraries/scan-settings - Get settings as non-admin", func(t *testing.T) {
		token := setup.RegularToken

		req := httptest.NewRequest("GET", "/api/libraries/scan-settings", nil)
		req.Header.Set("Authorization", "Bearer "+token)
		rec := httptest.NewRecorder()

		setup.Server.Config.Handler.ServeHTTP(rec, req)
		assert.Equal(t, http.StatusForbidden, rec.Code)
	})

	t.Run("GET /api/libraries/scan-settings - Get settings as admin", func(t *testing.T) {
		token := setup.Token

		req := httptest.NewRequest("GET", "/api/libraries/scan-settings", nil)
		req.Header.Set("Authorization", "Bearer "+token)
		rec := httptest.NewRecorder()

		setup.Server.Config.Handler.ServeHTTP(rec, req)
		assert.Equal(t, http.StatusOK, rec.Code)

		var response map[string]interface{}
		err := json.NewDecoder(rec.Body).Decode(&response)
		require.NoError(t, err)
		assert.Contains(t, response, "scan_poll_interval_seconds")
		assert.Contains(t, response, "auto_scan_enabled")
	})

	t.Run("PUT /api/libraries/scan-settings - Update without auth", func(t *testing.T) {
		payload := map[string]interface{}{
			"scan_poll_interval_seconds": 30,
			"auto_scan_enabled":          true,
		}
		jsonData, _ := json.Marshal(payload)

		req := httptest.NewRequest("PUT", "/api/libraries/scan-settings", bytes.NewBuffer(jsonData))
		req.Header.Set("Content-Type", "application/json")
		rec := httptest.NewRecorder()

		setup.Server.Config.Handler.ServeHTTP(rec, req)
		assert.Equal(t, http.StatusUnauthorized, rec.Code)
	})

	t.Run("PUT /api/libraries/scan-settings - Update as non-admin", func(t *testing.T) {
		token := setup.RegularToken

		payload := map[string]interface{}{
			"scan_poll_interval_seconds": 30,
			"auto_scan_enabled":          true,
		}
		jsonData, _ := json.Marshal(payload)

		req := httptest.NewRequest("PUT", "/api/libraries/scan-settings", bytes.NewBuffer(jsonData))
		req.Header.Set("Content-Type", "application/json")
		req.Header.Set("Authorization", "Bearer "+token)
		rec := httptest.NewRecorder()

		setup.Server.Config.Handler.ServeHTTP(rec, req)
		assert.Equal(t, http.StatusForbidden, rec.Code)
	})

	t.Run("PUT /api/libraries/scan-settings - Update with invalid frequency", func(t *testing.T) {
		token := setup.Token

		testCases := []struct {
			name                    string
			ScanPollIntervalSeconds int
		}{
			{"Frequency too low (0 seconds)", 0},
			{"Frequency too high (3601 seconds)", 3601},
			{"Frequency negative (-10)", -10},
		}

		for _, tc := range testCases {
			t.Run(tc.name, func(t *testing.T) {
				payload := map[string]interface{}{
					"scan_poll_interval_seconds": tc.ScanPollIntervalSeconds,
					"auto_scan_enabled":          true,
				}
				jsonData, _ := json.Marshal(payload)

				req := httptest.NewRequest("PUT", "/api/libraries/scan-settings", bytes.NewBuffer(jsonData))
				req.Header.Set("Content-Type", "application/json")
				req.Header.Set("Authorization", "Bearer "+token)
				rec := httptest.NewRecorder()

				setup.Server.Config.Handler.ServeHTTP(rec, req)
				assert.Equal(t, http.StatusBadRequest, rec.Code)
			})
		}
	})

	t.Run("PUT /api/libraries/scan-settings - Update with missing required field", func(t *testing.T) {
		token := setup.Token

		payload := map[string]interface{}{
			"auto_scan_enabled": true,
		}
		jsonData, _ := json.Marshal(payload)

		req := httptest.NewRequest("PUT", "/api/libraries/scan-settings", bytes.NewBuffer(jsonData))
		req.Header.Set("Content-Type", "application/json")
		req.Header.Set("Authorization", "Bearer "+token)
		rec := httptest.NewRecorder()

		setup.Server.Config.Handler.ServeHTTP(rec, req)
		assert.Equal(t, http.StatusBadRequest, rec.Code)
	})

	t.Run("PUT /api/libraries/scan-settings - Update with valid data", func(t *testing.T) {
		token := setup.Token

		testCases := []struct {
			name                    string
			ScanPollIntervalSeconds int
			autoScanEnabled         bool
		}{
			{"Valid frequency (1 second)", 1, true},
			{"Valid frequency (60 seconds)", 60, true},
			{"Valid frequency (3600 seconds)", 3600, true},
			{"Valid frequency (30 seconds)", 30, false},
			{"Valid frequency (300 seconds)", 300, true},
		}

		for _, tc := range testCases {
			t.Run(tc.name, func(t *testing.T) {
				payload := map[string]interface{}{
					"scan_poll_interval_seconds": tc.ScanPollIntervalSeconds,
					"auto_scan_enabled":          tc.autoScanEnabled,
				}
				jsonData, _ := json.Marshal(payload)

				req := httptest.NewRequest("PUT", "/api/libraries/scan-settings", bytes.NewBuffer(jsonData))
				req.Header.Set("Content-Type", "application/json")
				req.Header.Set("Authorization", "Bearer "+token)
				rec := httptest.NewRecorder()

				setup.Server.Config.Handler.ServeHTTP(rec, req)
				assert.Equal(t, http.StatusOK, rec.Code)

				var response map[string]interface{}
				err := json.NewDecoder(rec.Body).Decode(&response)
				require.NoError(t, err)
				assert.Equal(t, float64(tc.ScanPollIntervalSeconds), response["scan_poll_interval_seconds"])
				assert.Equal(t, tc.autoScanEnabled, response["auto_scan_enabled"])
			})
		}
	})

	t.Run("PUT /api/libraries/scan-settings - Update with invalid JSON", func(t *testing.T) {
		token := setup.Token

		invalidJSON := []byte(`{scan_poll_interval_seconds: 60, auto_scan_enabled: true}`)

		req := httptest.NewRequest("PUT", "/api/libraries/scan-settings", bytes.NewBuffer(invalidJSON))
		req.Header.Set("Content-Type", "application/json")
		req.Header.Set("Authorization", "Bearer "+token)
		rec := httptest.NewRecorder()

		setup.Server.Config.Handler.ServeHTTP(rec, req)
		assert.Equal(t, http.StatusBadRequest, rec.Code)
	})
}

// TestSystemSettingsIntegration tests the integration of system settings with the scheduler
func TestSystemSettingsIntegration(t *testing.T) {
	t.Run("System settings affect all libraries equally", func(t *testing.T) {
		settings := map[string]interface{}{
			"scan_poll_interval_seconds": 60,
			"auto_scan_enabled":          true,
		}

		assert.Equal(t, 60, settings["scan_poll_interval_seconds"])
		assert.Equal(t, true, settings["auto_scan_enabled"])
	})

	t.Run("Disabling auto scan stops all library scans", func(t *testing.T) {
		settings := map[string]interface{}{
			"scan_poll_interval_seconds": 60,
			"auto_scan_enabled":          false,
		}

		assert.Equal(t, false, settings["auto_scan_enabled"])
	})

	t.Run("Valid frequency range enforcement", func(t *testing.T) {
		validFrequencies := []int{1, 30, 60, 300, 600, 1800, 3600}
		invalidFrequencies := []int{0, -1, 3601, 5000}

		for _, freq := range validFrequencies {
			assert.True(t, freq >= 1 && freq <= 3600, "Frequency %d should be valid", freq)
		}

		for _, freq := range invalidFrequencies {
			assert.False(t, freq >= 1 && freq <= 3600, "Frequency %d should be invalid", freq)
		}
	})
}
