package handler

import (
	"bytes"
	"errors"
	"io"
	"log"
	"net/http"
	"net/http/httptest"
	"testing"
	"time"

	"github.com/seifghazi/claude-code-monitor/internal/config"
	"github.com/seifghazi/claude-code-monitor/internal/model"
)

type stubStorage struct {
	getSettingsFn  func() (*model.ProxySettings, error)
	saveSettingsFn func(settings *model.ProxySettings) error
	getCalls       int
	saveCalls      int
}

func (s *stubStorage) SaveRequest(*model.RequestLog) (string, error) { panic("unexpected call") }
func (s *stubStorage) GetRequests(int, int, string) ([]model.RequestLog, int, error) {
	panic("unexpected call")
}
func (s *stubStorage) GetAllRequests(string) ([]*model.RequestLog, error) { panic("unexpected call") }
func (s *stubStorage) GetRequestByShortID(string) (*model.RequestLog, string, error) {
	panic("unexpected call")
}
func (s *stubStorage) ClearRequests() (int, error) { panic("unexpected call") }
func (s *stubStorage) UpdateRequestWithGrading(string, *model.PromptGrade) error {
	panic("unexpected call")
}
func (s *stubStorage) UpdateRequestWithResponse(*model.RequestLog) error  { panic("unexpected call") }
func (s *stubStorage) DeleteRequestsOlderThan(time.Duration) (int, error) { panic("unexpected call") }
func (s *stubStorage) GetDatabaseStats() (map[string]interface{}, error)  { panic("unexpected call") }
func (s *stubStorage) GetUsageStats(string, string, string, string) (*model.UsageStats, error) {
	panic("unexpected call")
}
func (s *stubStorage) GetRequestsSummary(string) ([]*model.RequestSummary, error) {
	panic("unexpected call")
}
func (s *stubStorage) GetRequestsSummaryPaginated(string, string, string, int, int) ([]*model.RequestSummary, int, error) {
	panic("unexpected call")
}
func (s *stubStorage) GetStats(string, string, string) (*model.DashboardStats, error) {
	panic("unexpected call")
}
func (s *stubStorage) GetHourlyStats(string, string, int, string) (*model.HourlyStatsResponse, error) {
	panic("unexpected call")
}
func (s *stubStorage) GetModelStats(string, string, string) (*model.ModelStatsResponse, error) {
	panic("unexpected call")
}
func (s *stubStorage) GetLatestRequestDate() (*time.Time, error)   { panic("unexpected call") }
func (s *stubStorage) GetDistinctOrganizations() ([]string, error) { panic("unexpected call") }
func (s *stubStorage) GetSettings() (*model.ProxySettings, error) {
	s.getCalls++
	if s.getSettingsFn != nil {
		return s.getSettingsFn()
	}
	return &model.ProxySettings{}, nil
}
func (s *stubStorage) SaveSettings(settings *model.ProxySettings) error {
	s.saveCalls++
	if s.saveSettingsFn != nil {
		return s.saveSettingsFn(settings)
	}
	return nil
}
func (s *stubStorage) GetConfig() *config.StorageConfig { return &config.StorageConfig{} }
func (s *stubStorage) EnsureDirectoryExists() error     { return nil }
func (s *stubStorage) Close() error                     { return nil }

func TestGetCachedSettingsCachesFirstLoad(t *testing.T) {
	storage := &stubStorage{
		getSettingsFn: func() (*model.ProxySettings, error) {
			return &model.ProxySettings{
				RequestHeaderRules: []model.HeaderRule{{Header: "X-Test", Action: "set", Value: "1", Enabled: true}},
			}, nil
		},
	}
	h := &Handler{
		storageService: storage,
		logger:         log.New(io.Discard, "", 0),
	}

	first := h.GetCachedSettings()
	second := h.GetCachedSettings()

	if storage.getCalls != 1 {
		t.Fatalf("expected one storage read, got %d", storage.getCalls)
	}
	if len(first.RequestHeaderRules) != 1 || len(second.RequestHeaderRules) != 1 {
		t.Fatalf("expected cached settings to be returned, got %#v %#v", first, second)
	}
}

func TestSaveSettingsUpdatesCache(t *testing.T) {
	storage := &stubStorage{}
	h := &Handler{
		storageService: storage,
		logger:         log.New(io.Discard, "", 0),
	}

	body := []byte(`{"requestHeaderRules":[{"header":"X-New","action":"set","value":"abc","enabled":true}]}`)
	req := httptest.NewRequest(http.MethodPut, "/api/settings", bytes.NewReader(body))
	rr := httptest.NewRecorder()

	h.SaveSettings(rr, req)

	if rr.Code != http.StatusOK {
		t.Fatalf("expected 200, got %d", rr.Code)
	}
	if storage.saveCalls != 1 {
		t.Fatalf("expected one settings save, got %d", storage.saveCalls)
	}

	cached := h.GetCachedSettings()
	if storage.getCalls != 0 {
		t.Fatalf("expected cached settings to avoid storage read, got %d reads", storage.getCalls)
	}
	if len(cached.RequestHeaderRules) != 1 || cached.RequestHeaderRules[0].Header != "X-New" {
		t.Fatalf("expected cache updated from save, got %#v", cached)
	}
}

func TestGetSettingsReturnsStorageError(t *testing.T) {
	storage := &stubStorage{
		getSettingsFn: func() (*model.ProxySettings, error) {
			return nil, errors.New("boom")
		},
	}
	h := &Handler{
		storageService: storage,
		logger:         log.New(io.Discard, "", 0),
	}

	req := httptest.NewRequest(http.MethodGet, "/api/settings", nil)
	rr := httptest.NewRecorder()

	h.GetSettings(rr, req)

	if rr.Code != http.StatusInternalServerError {
		t.Fatalf("expected 500, got %d", rr.Code)
	}

	var response model.ErrorResponse
	decodeJSONBody(t, rr, &response)
	if response.Error != "Failed to get settings" {
		t.Fatalf("unexpected error response: %#v", response)
	}
}

func TestSaveSettingsRejectsInvalidBodyAndStorageFailures(t *testing.T) {
	t.Run("invalid json", func(t *testing.T) {
		h := &Handler{
			storageService: &stubStorage{},
			logger:         log.New(io.Discard, "", 0),
		}

		req := httptest.NewRequest(http.MethodPut, "/api/settings", bytes.NewBufferString(`{"requestHeaderRules":`))
		rr := httptest.NewRecorder()

		h.SaveSettings(rr, req)

		if rr.Code != http.StatusBadRequest {
			t.Fatalf("expected 400, got %d", rr.Code)
		}

		var response model.ErrorResponse
		decodeJSONBody(t, rr, &response)
		if response.Error != "Invalid request body" {
			t.Fatalf("unexpected error response: %#v", response)
		}
	})

	t.Run("storage error", func(t *testing.T) {
		storage := &stubStorage{
			saveSettingsFn: func(settings *model.ProxySettings) error {
				return errors.New("boom")
			},
		}
		h := &Handler{
			storageService: storage,
			logger:         log.New(io.Discard, "", 0),
		}

		req := httptest.NewRequest(http.MethodPut, "/api/settings", bytes.NewBufferString(`{"responseHeaderRules":[{"header":"X-Test","action":"set","value":"1","enabled":true}]}`))
		rr := httptest.NewRecorder()

		h.SaveSettings(rr, req)

		if rr.Code != http.StatusInternalServerError {
			t.Fatalf("expected 500, got %d", rr.Code)
		}
		if storage.saveCalls != 1 {
			t.Fatalf("expected one settings save attempt, got %d", storage.saveCalls)
		}

		var response model.ErrorResponse
		decodeJSONBody(t, rr, &response)
		if response.Error != "Failed to save settings" {
			t.Fatalf("unexpected error response: %#v", response)
		}
	})
}
