package server

import (
	"encoding/json"
	"testing"
)

func TestAdminTriggerGC(t *testing.T) {
	database := openAdminTestDB(t)
	router, _ := buildAdminRouter(t, database)

	rr := adminReq(t, router, "POST", "/v1/gc", "")
	if rr.Code != 202 {
		t.Fatalf("status: got %d, want 202; body: %s", rr.Code, rr.Body.String())
	}

	var resp gcTriggerResponse
	if err := json.NewDecoder(rr.Body).Decode(&resp); err != nil {
		t.Fatalf("decode: %v", err)
	}
	if resp.ID == "" {
		t.Fatal("expected non-empty GC ID")
	}
}

func TestAdminTriggerGCConflict(t *testing.T) {
	database := openAdminTestDB(t)
	router, _ := buildAdminRouter(t, database)

	// First trigger should succeed.
	rr := adminReq(t, router, "POST", "/v1/gc", "")
	if rr.Code != 202 {
		t.Fatalf("first trigger status: got %d, want 202", rr.Code)
	}

	// Second trigger should conflict because GC is still "running".
	rr = adminReq(t, router, "POST", "/v1/gc", "")
	if rr.Code != 409 {
		t.Fatalf("second trigger status: got %d, want 409; body: %s", rr.Code, rr.Body.String())
	}
}

func TestAdminGCStatus(t *testing.T) {
	database := openAdminTestDB(t)
	router, _ := buildAdminRouter(t, database)

	// Before triggering GC.
	rr := adminReq(t, router, "GET", "/v1/gc/status", "")
	if rr.Code != 200 {
		t.Fatalf("status: got %d, want 200", rr.Code)
	}

	var resp gcStatusResponse
	if err := json.NewDecoder(rr.Body).Decode(&resp); err != nil {
		t.Fatalf("decode: %v", err)
	}
	if resp.Running {
		t.Fatal("expected running=false before trigger")
	}

	// Trigger GC.
	rr = adminReq(t, router, "POST", "/v1/gc", "")
	if rr.Code != 202 {
		t.Fatalf("trigger status: got %d, want 202", rr.Code)
	}

	// After triggering GC.
	rr = adminReq(t, router, "GET", "/v1/gc/status", "")
	if rr.Code != 200 {
		t.Fatalf("status: got %d, want 200", rr.Code)
	}

	if err := json.NewDecoder(rr.Body).Decode(&resp); err != nil {
		t.Fatalf("decode: %v", err)
	}
	if !resp.Running {
		t.Fatal("expected running=true after trigger")
	}
}

func TestAdminGCNonAdmin(t *testing.T) {
	database := openAdminTestDB(t)
	router := buildNonAdminRouter(t, database)

	rr := adminReq(t, router, "POST", "/v1/gc", "")
	if rr.Code != 403 {
		t.Fatalf("trigger status: got %d, want 403", rr.Code)
	}

	rr = adminReq(t, router, "GET", "/v1/gc/status", "")
	if rr.Code != 403 {
		t.Fatalf("status status: got %d, want 403", rr.Code)
	}
}
