package api

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

	"github.com/jackc/pgx/v5/pgtype"

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

// callEvents invokes h.handleEvents directly, injecting `user` via the same
// context key RequireUser populates in production. Mirrors the pattern in
// me_test.go (userCtxKeyForTest comes from auth_test.go).
func callEvents(h *handlers, user dbq.User, body []byte) *httptest.ResponseRecorder {
	req := httptest.NewRequest(http.MethodPost, "/api/events", bytes.NewReader(body))
	req.Header.Set("Content-Type", "application/json")
	req = withUser(req, user)
	w := httptest.NewRecorder()
	h.handleEvents(w, req)
	return w
}

func TestHandleEvents_PlayStartedReturnsIDs(t *testing.T) {
	h, pool := testHandlers(t)
	truncateLibrary(t, pool)
	user := seedUser(t, pool, "alice", "x", false)
	artist := seedArtist(t, pool, "Beatles")
	album := seedAlbum(t, pool, artist.ID, "Abbey Road", 1969)
	track := seedTrack(t, pool, album.ID, artist.ID, "Something", 3, 183_000)

	body, _ := json.Marshal(map[string]any{
		"type":     "play_started",
		"track_id": uuidToString(track.ID),
	})
	w := callEvents(h, user, body)
	if w.Code != http.StatusOK {
		t.Fatalf("status = %d body=%s", w.Code, w.Body.String())
	}
	var resp struct {
		PlayEventID string `json:"play_event_id"`
		SessionID   string `json:"session_id"`
	}
	if err := json.Unmarshal(w.Body.Bytes(), &resp); err != nil {
		t.Fatalf("decode: %v", err)
	}
	if resp.PlayEventID == "" || resp.SessionID == "" {
		t.Errorf("ids empty: %+v", resp)
	}
}

func TestHandleEvents_PlayEndedClosesRow(t *testing.T) {
	h, pool := testHandlers(t)
	truncateLibrary(t, pool)
	user := seedUser(t, pool, "alice", "x", false)
	artist := seedArtist(t, pool, "Beatles")
	album := seedAlbum(t, pool, artist.ID, "Abbey Road", 1969)
	track := seedTrack(t, pool, album.ID, artist.ID, "Something", 3, 183_000)

	startedID := postPlayStartedHelper(t, h, user, track.ID)

	body, _ := json.Marshal(map[string]any{
		"type":               "play_ended",
		"play_event_id":      startedID,
		"duration_played_ms": 180_000,
	})
	w := callEvents(h, user, body)
	if w.Code != http.StatusOK {
		t.Fatalf("ended status = %d body=%s", w.Code, w.Body.String())
	}
}

func TestHandleEvents_MissingTypeIs400(t *testing.T) {
	h, pool := testHandlers(t)
	user := seedUser(t, pool, "alice", "x", false)
	body, _ := json.Marshal(map[string]any{"track_id": "00000000-0000-0000-0000-000000000000"})
	w := callEvents(h, user, body)
	if w.Code != http.StatusBadRequest {
		t.Errorf("status = %d", w.Code)
	}
}

func TestHandleEvents_PlayStartedWithUnknownTrackIs404(t *testing.T) {
	h, pool := testHandlers(t)
	user := seedUser(t, pool, "alice", "x", false)
	body, _ := json.Marshal(map[string]any{
		"type":     "play_started",
		"track_id": "00000000-0000-0000-0000-000000000000",
	})
	w := callEvents(h, user, body)
	if w.Code != http.StatusNotFound {
		t.Errorf("status = %d", w.Code)
	}
}

func TestHandleEvents_PlayEndedOnOtherUsersRowIs403(t *testing.T) {
	h, pool := testHandlers(t)
	truncateLibrary(t, pool)
	alice := seedUser(t, pool, "alice", "x", false)
	bob := seedUser(t, pool, "bob", "x", false)
	artist := seedArtist(t, pool, "X")
	album := seedAlbum(t, pool, artist.ID, "X", 1990)
	track := seedTrack(t, pool, album.ID, artist.ID, "X", 1, 100_000)

	startedID := postPlayStartedHelper(t, h, alice, track.ID)

	body, _ := json.Marshal(map[string]any{
		"type":               "play_ended",
		"play_event_id":      startedID,
		"duration_played_ms": 50_000,
	})
	w := callEvents(h, bob, body)
	if w.Code != http.StatusForbidden {
		t.Errorf("status = %d, want 403", w.Code)
	}
}

func postPlayStartedHelper(t *testing.T, h *handlers, user dbq.User, trackID pgtype.UUID) string {
	t.Helper()
	body, _ := json.Marshal(map[string]any{
		"type":     "play_started",
		"track_id": uuidToString(trackID),
	})
	w := callEvents(h, user, body)
	if w.Code != http.StatusOK {
		t.Fatalf("play_started status = %d body=%s", w.Code, w.Body.String())
	}
	var resp struct {
		PlayEventID string `json:"play_event_id"`
	}
	_ = json.Unmarshal(w.Body.Bytes(), &resp)
	return resp.PlayEventID
}
