package lkemulator_test

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

	"git.zetit.ru/zuevav/Bridge-and-Join-s/internal/lkemulator"
)

func TestCallbackUpdatesStore(t *testing.T) {
	srv, err := lkemulator.NewServer(lkemulator.ServerConfig{
		Addr:       ":0",
		GatewayURL: "http://example.invalid",
	})
	if err != nil {
		t.Fatal(err)
	}

	// Положим заявку в store вручную.
	c := &lkemulator.Claim{
		ID:        "local-1",
		GatewayID: "gw-abc",
		Status:    "submitted_to_nsd",
		CreatedAt: time.Now(),
		UpdatedAt: time.Now(),
	}
	srv.Store().Add(c)

	body := map[string]any{
		"claim_id":   "gw-abc",
		"new_status": "confirmed",
		"updated_at": time.Now().Format(time.RFC3339),
		"nsd_response": map[string]any{
			"guid":        "c02a1d5e-c2af-4799-bab4-953f133c5133",
			"status_code": "INFO",
			"responses":   []map[string]any{{"reference_id": "M2M2026030200001", "code": "01", "text": "ok"}},
		},
	}
	raw, _ := json.Marshal(body)
	w := httptest.NewRecorder()
	req := httptest.NewRequest(http.MethodPatch, "/api/v1/back_office/claims/gw-abc", bytes.NewReader(raw))
	srv.Mux().ServeHTTP(w, req)

	if w.Code != http.StatusOK {
		t.Fatalf("callback code=%d body=%s", w.Code, w.Body.String())
	}

	got := srv.Store().Get("local-1")
	if got.Status != "confirmed" {
		t.Errorf("статус не обновился, got=%s", got.Status)
	}
	if got.LastCallback == nil {
		t.Fatal("LastCallback nil")
	}
	if len(got.LastCallback.Responses) != 1 {
		t.Errorf("ожидался 1 response, получено %d", len(got.LastCallback.Responses))
	}
}

func TestCallbackUnknownClaim(t *testing.T) {
	srv, err := lkemulator.NewServer(lkemulator.ServerConfig{Addr: ":0", GatewayURL: "http://example.invalid"})
	if err != nil {
		t.Fatal(err)
	}
	w := httptest.NewRecorder()
	req := httptest.NewRequest(http.MethodPatch, "/api/v1/back_office/claims/unknown", strings.NewReader(`{"new_status":"confirmed"}`))
	srv.Mux().ServeHTTP(w, req)
	if w.Code != http.StatusNotFound {
		t.Errorf("ожидался 404, получено %d", w.Code)
	}
}

func TestHomePageEmpty(t *testing.T) {
	srv, err := lkemulator.NewServer(lkemulator.ServerConfig{Addr: ":0", GatewayURL: "http://example.invalid"})
	if err != nil {
		t.Fatal(err)
	}
	w := httptest.NewRecorder()
	req := httptest.NewRequest(http.MethodGet, "/", nil)
	srv.Mux().ServeHTTP(w, req)
	if w.Code != http.StatusOK {
		t.Errorf("home: %d", w.Code)
	}
	if !strings.Contains(w.Body.String(), "Заявок ещё нет") {
		t.Errorf("ожидалось сообщение об отсутствии заявок")
	}
}

func TestHealthz(t *testing.T) {
	srv, err := lkemulator.NewServer(lkemulator.ServerConfig{Addr: ":0", GatewayURL: "http://example.invalid"})
	if err != nil {
		t.Fatal(err)
	}
	w := httptest.NewRecorder()
	req := httptest.NewRequest(http.MethodGet, "/healthz", nil)
	srv.Mux().ServeHTTP(w, req)
	if w.Code != http.StatusOK {
		t.Errorf("healthz: %d", w.Code)
	}
}
