//go:build test

package admin

import (
	"net/http"
	"testing"

	"crussell/testutils"
	"crussell/testutils/fixtures"
)

func TestPatchTests_CRUD(t *testing.T) {

	ctx, tx := testutils.SetupTestTx(t)
	// Create a service to link
	serviceID, err := fixtures.CreateTestService(tx)
	if err != nil {
		t.Fatalf("failed to create service: %v", err)
	}

	req := CreatePatchTestRequest{
		Name:                "Test Patch Test",
		Description:         strPtr("Description"),
		NoticeDurationHours: 24,
		ExpiryMonths:        6,
		ServiceIDs:          []string{serviceID},
	}
	w := makeAdminRequest(http.HandlerFunc(CreatePatchTest), "POST", "/api/admin/patch-tests", req, ctx)
	if w.Code != http.StatusCreated {
		t.Fatalf("expected 201, got %d", w.Code)
	}

	var created struct {
		ID string `json:"id"`
	}
	parseResponseBody(w, &created)

	w = makeAdminRequest(http.HandlerFunc(GetPatchTests), "GET", "/api/admin/patch-tests", nil, ctx)
	if w.Code != http.StatusOK {
		t.Fatalf("expected 200, got %d", w.Code)
	}

	var list []PatchTest
	parseResponseBody(w, &list)
	if len(list) != 1 {
		t.Errorf("expected 1 patch test, got %d", len(list))
	}

	newName := "Updated Name"
	updateReq := UpdatePatchTestRequest{Name: &newName}
	w = makeAdminRequest(http.HandlerFunc(UpdatePatchTest), "PUT", "/api/admin/patch-tests/"+created.ID, updateReq, ctx)
	if w.Code != http.StatusNoContent {
		t.Fatalf("expected 204, got %d, body: %s", w.Code, w.Body.String())
	}

	w = makeAdminRequest(http.HandlerFunc(DeletePatchTest), "DELETE", "/api/admin/patch-tests/"+created.ID, nil, ctx)
	if w.Code != http.StatusNoContent {
		t.Fatalf("expected 204, got %d", w.Code)
	}
}

func strPtr(s string) *string {
	return &s
}
