// server/backend/internal/httpapi/manage/override_test.go
package manage_test

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

	"git.az-it.net/az/morz-infoboard/server/backend/internal/httpapi/manage"
	"git.az-it.net/az/morz-infoboard/server/backend/internal/store"
)

// --- Mocks ---

type mockGlobalOverrideStore struct {
	current      *store.GlobalOverride
	upsertCalled bool
	deleteCalled bool
}

func (m *mockGlobalOverrideStore) Get(_ context.Context) (*store.GlobalOverride, error) {
	return m.current, nil
}
func (m *mockGlobalOverrideStore) Upsert(_ context.Context, t string, u time.Time) error {
	m.current = &store.GlobalOverride{Type: t, Until: u}
	m.upsertCalled = true
	return nil
}
func (m *mockGlobalOverrideStore) Delete(_ context.Context) error {
	m.current = nil
	m.deleteCalled = true
	return nil
}

// --- Tests ---

func TestHandleGetGlobalOverride_None(t *testing.T) {
	h := manage.HandleGetGlobalOverride(&mockGlobalOverrideStore{})
	req := httptest.NewRequest(http.MethodGet, "/api/v1/global-override", nil)
	w := httptest.NewRecorder()
	h.ServeHTTP(w, req)
	if w.Code != http.StatusNoContent {
		t.Fatalf("want 204, got %d", w.Code)
	}
}

func TestHandleGetGlobalOverride_Active(t *testing.T) {
	until := time.Now().Add(time.Hour)
	m := &mockGlobalOverrideStore{
		current: &store.GlobalOverride{Type: "off", Until: until},
	}
	h := manage.HandleGetGlobalOverride(m)
	req := httptest.NewRequest(http.MethodGet, "/api/v1/global-override", nil)
	w := httptest.NewRecorder()
	h.ServeHTTP(w, req)
	if w.Code != http.StatusOK {
		t.Fatalf("want 200, got %d", w.Code)
	}
	var resp store.GlobalOverride
	if err := json.NewDecoder(w.Body).Decode(&resp); err != nil {
		t.Fatal("decode response:", err)
	}
	if resp.Type != "off" {
		t.Errorf("want type=off, got %q", resp.Type)
	}
}

func TestHandleSetGlobalOverride_InvalidType(t *testing.T) {
	h := manage.HandleSetGlobalOverride(&mockGlobalOverrideStore{}, nil, nil)
	body := `{"type":"maybe","until":"` + time.Now().Add(time.Hour).Format(time.RFC3339) + `"}`
	req := httptest.NewRequest(http.MethodPost, "/api/v1/global-override", bytes.NewBufferString(body))
	req.Header.Set("Content-Type", "application/json")
	w := httptest.NewRecorder()
	h.ServeHTTP(w, req)
	if w.Code != http.StatusBadRequest {
		t.Fatalf("want 400, got %d", w.Code)
	}
}

func TestHandleDeleteGlobalOverride(t *testing.T) {
	m := &mockGlobalOverrideStore{
		current: &store.GlobalOverride{Type: "off", Until: time.Now().Add(time.Hour)},
	}
	h := manage.HandleDeleteGlobalOverride(m)
	req := httptest.NewRequest(http.MethodDelete, "/api/v1/global-override", nil)
	w := httptest.NewRecorder()
	h.ServeHTTP(w, req)
	if w.Code != http.StatusNoContent {
		t.Fatalf("want 204, got %d", w.Code)
	}
	if !m.deleteCalled {
		t.Error("Delete() was not called")
	}
}
