package api

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

	"git.fabledsword.com/bvandeusen/minstrel/internal/db/dbq"
)

func TestHandleGetMe_ReturnsAuthenticatedUser(t *testing.T) {
	h, pool := testHandlers(t)
	user := seedUser(t, pool, "alice", "hunter2", true)

	req := httptest.NewRequest(http.MethodGet, "/api/me", nil)
	req = req.WithContext(context.WithValue(req.Context(), userCtxKeyForTest(), user))
	w := httptest.NewRecorder()
	h.handleGetMe(w, req)

	if w.Code != http.StatusOK {
		t.Fatalf("status = %d body = %s", w.Code, w.Body.String())
	}
	var got UserView
	if err := json.Unmarshal(w.Body.Bytes(), &got); err != nil {
		t.Fatalf("decode: %v", err)
	}
	if got.Username != "alice" || !got.IsAdmin {
		t.Errorf("user = %+v, want alice/admin", got)
	}
}

func TestHandleGetMe_MissingContextReturns500(t *testing.T) {
	h, _ := testHandlers(t)
	req := httptest.NewRequest(http.MethodGet, "/api/me", nil)
	w := httptest.NewRecorder()
	h.handleGetMe(w, req)

	if w.Code != http.StatusInternalServerError {
		t.Errorf("status = %d, want 500 (context should be populated by RequireUser)", w.Code)
	}
	_ = dbq.User{} // keep the import used
}
