package api

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

	"gitea.dooplex.hu/admin/felhom-hub/internal/store"
)

// The one-time offsite password is served once to the authenticated customer, then 404s; a wrong/absent or
// cross-customer key is rejected.
func TestOffsite_ConsumePassword(t *testing.T) {
	h, st, _ := newTestHandler(t)
	st.SaveCustomerConfig(&store.CustomerConfig{CustomerID: "c1", APIKey: "ckey", RetrievalPassword: "pp"})
	st.SaveCustomerConfig(&store.CustomerConfig{CustomerID: "c2", APIKey: "ckey2", RetrievalPassword: "pp2"})
	st.SaveOneTimeSecret("c1", "the-transient-pw")

	do := func(token string) *httptest.ResponseRecorder {
		req := httptest.NewRequest(http.MethodPost, "/api/v1/offsite/consume-password/c1", nil)
		if token != "" {
			req.Header.Set("Authorization", "Bearer "+token)
		}
		rr := httptest.NewRecorder()
		h.ServeHTTP(rr, req)
		return rr
	}

	if rr := do(""); rr.Code != http.StatusUnauthorized {
		t.Fatalf("no auth → %d, want 401", rr.Code)
	}
	if rr := do("wrongkey"); rr.Code != http.StatusUnauthorized {
		t.Fatalf("wrong key → %d, want 401", rr.Code)
	}
	if rr := do("ckey2"); rr.Code != http.StatusUnauthorized {
		t.Fatalf("cross-customer key → %d, want 401", rr.Code)
	}
	// first (authorized) consume → 200 + the password
	rr := do("ckey")
	if rr.Code != http.StatusOK {
		t.Fatalf("consume → %d, want 200", rr.Code)
	}
	var body map[string]string
	if err := json.Unmarshal(rr.Body.Bytes(), &body); err != nil || body["password"] != "the-transient-pw" {
		t.Fatalf("body = %q (%v)", rr.Body.String(), err)
	}
	// second consume → 404 (single use)
	if rr2 := do("ckey"); rr2.Code != http.StatusNotFound {
		t.Fatalf("second consume → %d, want 404", rr2.Code)
	}
}
