package purchasing

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

	"github.com/go-chi/chi/v5"
)

func TestDeleteOrderHandlerReturnsBodyless204(t *testing.T) {
	s := svc()
	s.store.(*fakeStore).orders[1] = &PurchaseOrder{ID: 1, Status: "draft"}
	r := chi.NewRouter()
	r.Delete("/purchase-orders/{id}", NewHandler(s).DeleteOrder)
	res := httptest.NewRecorder()
	r.ServeHTTP(res, httptest.NewRequest(http.MethodDelete, "/purchase-orders/1", nil))
	if res.Code != http.StatusNoContent || res.Body.Len() != 0 {
		t.Fatalf("delete = status %d body %q, want 204 with empty body", res.Code, res.Body.String())
	}
}

func TestListDebtsHandlerUsesCanonicalCollectionEnvelope(t *testing.T) {
	res := httptest.NewRecorder()
	NewHandler(svc()).ListDebts(res, httptest.NewRequest(http.MethodGet, "/?page=1&per_page=20", nil))
	if res.Code != http.StatusOK {
		t.Fatalf("status = %d, want 200", res.Code)
	}
	var body struct {
		Data []json.RawMessage `json:"data"`
		Meta struct {
			Pagination json.RawMessage `json:"pagination"`
		} `json:"meta"`
	}
	if err := json.NewDecoder(strings.NewReader(res.Body.String())).Decode(&body); err != nil {
		t.Fatal(err)
	}
	if body.Data == nil || len(body.Meta.Pagination) == 0 || string(body.Meta.Pagination) == "null" {
		t.Fatalf("envelope = %s, want data array and meta.pagination", res.Body.String())
	}
}
