package api

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

	"github.com/go-chi/chi/v5"

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

func callLike(h *handlers, user dbq.User, method, path string) *httptest.ResponseRecorder {
	req := httptest.NewRequest(method, path, nil)
	req = withUser(req, user)
	w := httptest.NewRecorder()
	likesRouter(h).ServeHTTP(w, req)
	return w
}

// likesRouter matches the routes registered in Mount but without RequireUser
// so tests can inject the user via context directly.
func likesRouter(h *handlers) http.Handler {
	r := chi.NewRouter()
	r.Post("/api/likes/tracks/{id}", h.handleLikeTrack)
	r.Delete("/api/likes/tracks/{id}", h.handleUnlikeTrack)
	r.Post("/api/likes/albums/{id}", h.handleLikeAlbum)
	r.Delete("/api/likes/albums/{id}", h.handleUnlikeAlbum)
	r.Post("/api/likes/artists/{id}", h.handleLikeArtist)
	r.Delete("/api/likes/artists/{id}", h.handleUnlikeArtist)
	r.Get("/api/likes/tracks", h.handleListLikedTracks)
	r.Get("/api/likes/albums", h.handleListLikedAlbums)
	r.Get("/api/likes/artists", h.handleListLikedArtists)
	r.Get("/api/likes/ids", h.handleGetLikedIDs)
	return r
}

func TestLikeTrack_Idempotent(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)

	w := callLike(h, user, http.MethodPost, "/api/likes/tracks/"+uuidToString(track.ID))
	if w.Code != http.StatusNoContent {
		t.Fatalf("first like: status = %d body=%s", w.Code, w.Body.String())
	}
	w = callLike(h, user, http.MethodPost, "/api/likes/tracks/"+uuidToString(track.ID))
	if w.Code != http.StatusNoContent {
		t.Errorf("second like (idempotent): status = %d", w.Code)
	}
	var count int
	_ = pool.QueryRow(context.Background(),
		"SELECT count(*) FROM general_likes WHERE user_id=$1", user.ID).Scan(&count)
	if count != 1 {
		t.Errorf("rows = %d, want 1", count)
	}
}

func TestLikeTrack_BadUUIDIs400(t *testing.T) {
	h, pool := testHandlers(t)
	user := seedUser(t, pool, "alice", "x", false)
	w := callLike(h, user, http.MethodPost, "/api/likes/tracks/not-a-uuid")
	if w.Code != http.StatusBadRequest {
		t.Errorf("status = %d", w.Code)
	}
}

func TestLikeTrack_UnknownTrackIs404(t *testing.T) {
	h, pool := testHandlers(t)
	truncateLibrary(t, pool)
	user := seedUser(t, pool, "alice", "x", false)
	w := callLike(h, user, http.MethodPost, "/api/likes/tracks/00000000-0000-0000-0000-000000000000")
	if w.Code != http.StatusNotFound {
		t.Errorf("status = %d", w.Code)
	}
}

func TestUnlikeTrack_IdempotentEvenWhenAbsent(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)

	w := callLike(h, user, http.MethodDelete, "/api/likes/tracks/"+uuidToString(track.ID))
	if w.Code != http.StatusNoContent {
		t.Errorf("status = %d", w.Code)
	}
}

func TestListLikedTracks_PaginatedAndSortedDescByLikedAt(t *testing.T) {
	h, pool := testHandlers(t)
	truncateLibrary(t, pool)
	user := seedUser(t, pool, "alice", "x", false)
	artist := seedArtist(t, pool, "X")
	album := seedAlbum(t, pool, artist.ID, "X", 1990)
	t1 := seedTrack(t, pool, album.ID, artist.ID, "First", 1, 100_000)
	t2 := seedTrack(t, pool, album.ID, artist.ID, "Second", 2, 100_000)

	// Like t1 then t2 — newest should come first.
	_ = callLike(h, user, http.MethodPost, "/api/likes/tracks/"+uuidToString(t1.ID))
	_ = callLike(h, user, http.MethodPost, "/api/likes/tracks/"+uuidToString(t2.ID))

	w := callLike(h, user, http.MethodGet, "/api/likes/tracks?limit=10&offset=0")
	if w.Code != http.StatusOK {
		t.Fatalf("status = %d body=%s", w.Code, w.Body.String())
	}
	var resp struct {
		Items  []TrackRef `json:"items"`
		Total  int        `json:"total"`
		Limit  int        `json:"limit"`
		Offset int        `json:"offset"`
	}
	_ = json.Unmarshal(w.Body.Bytes(), &resp)
	if resp.Total != 2 || len(resp.Items) != 2 {
		t.Fatalf("shape: %+v", resp)
	}
	if resp.Items[0].Title != "Second" {
		t.Errorf("first item = %q, want %q (most recent)", resp.Items[0].Title, "Second")
	}
}

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

	_ = callLike(h, user, http.MethodPost, "/api/likes/tracks/"+uuidToString(track.ID))
	_ = callLike(h, user, http.MethodPost, "/api/likes/albums/"+uuidToString(album.ID))
	_ = callLike(h, user, http.MethodPost, "/api/likes/artists/"+uuidToString(artist.ID))

	w := callLike(h, user, http.MethodGet, "/api/likes/ids")
	if w.Code != http.StatusOK {
		t.Fatalf("status = %d", w.Code)
	}
	var resp struct {
		TrackIDs  []string `json:"track_ids"`
		AlbumIDs  []string `json:"album_ids"`
		ArtistIDs []string `json:"artist_ids"`
	}
	_ = json.Unmarshal(w.Body.Bytes(), &resp)
	if len(resp.TrackIDs) != 1 || len(resp.AlbumIDs) != 1 || len(resp.ArtistIDs) != 1 {
		t.Errorf("ids = %+v", resp)
	}
}

func TestGetLikedIDs_CrossUserIsolation(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, "T", 1, 100_000)

	// Alice likes the track.
	_ = callLike(h, alice, http.MethodPost, "/api/likes/tracks/"+uuidToString(track.ID))
	// Bob queries his ids — should be empty.
	w := callLike(h, bob, http.MethodGet, "/api/likes/ids")
	var resp struct {
		TrackIDs []string `json:"track_ids"`
	}
	_ = json.Unmarshal(w.Body.Bytes(), &resp)
	if len(resp.TrackIDs) != 0 {
		t.Errorf("bob's track_ids should be empty, got %v", resp.TrackIDs)
	}
}

func TestLikeAlbumAndArtist_HappyPath(t *testing.T) {
	h, pool := testHandlers(t)
	truncateLibrary(t, pool)
	user := seedUser(t, pool, "alice", "x", false)
	artist := seedArtist(t, pool, "X")
	album := seedAlbum(t, pool, artist.ID, "X", 1990)

	w := callLike(h, user, http.MethodPost, "/api/likes/albums/"+uuidToString(album.ID))
	if w.Code != http.StatusNoContent {
		t.Errorf("album: status = %d", w.Code)
	}
	w = callLike(h, user, http.MethodPost, "/api/likes/artists/"+uuidToString(artist.ID))
	if w.Code != http.StatusNoContent {
		t.Errorf("artist: status = %d", w.Code)
	}
	w = callLike(h, user, http.MethodGet, "/api/likes/albums?limit=10")
	var resp struct {
		Total int `json:"total"`
	}
	_ = json.Unmarshal(w.Body.Bytes(), &resp)
	if resp.Total != 1 {
		t.Errorf("album total = %d", resp.Total)
	}
}

func TestLikeTrack_DuringOpenPlayEvent_WritesContextualLike(t *testing.T) {
	h, pool := testHandlers(t)
	truncateLibrary(t, pool)
	user := seedUser(t, pool, "alice", "x", false)
	artist := seedArtist(t, pool, "X")
	album := seedAlbum(t, pool, artist.ID, "X", 1990)
	playing := seedTrack(t, pool, album.ID, artist.ID, "Now Playing", 1, 100_000)
	other := seedTrack(t, pool, album.ID, artist.ID, "Other", 2, 100_000)

	// Simulate a play_started: insert via the writer.
	w := callEvents(h, user, []byte(`{"type":"play_started","track_id":"`+uuidToString(playing.ID)+`"}`))
	if w.Code != http.StatusOK {
		t.Fatalf("play_started failed: %d %s", w.Code, w.Body.String())
	}
	// Like the OTHER track. With an open play_event for `playing`,
	// the contextual_likes row should reference `other` and the playing
	// track's session vector.
	if r := callLike(h, user, http.MethodPost, "/api/likes/tracks/"+uuidToString(other.ID)); r.Code != http.StatusNoContent {
		t.Fatalf("like: %d", r.Code)
	}
	var count int
	_ = pool.QueryRow(context.Background(),
		"SELECT count(*) FROM contextual_likes WHERE user_id=$1 AND track_id=$2", user.ID, other.ID).Scan(&count)
	if count != 1 {
		t.Errorf("contextual_likes count = %d, want 1", count)
	}
}

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

	if r := callLike(h, user, http.MethodPost, "/api/likes/tracks/"+uuidToString(track.ID)); r.Code != http.StatusNoContent {
		t.Fatalf("like: %d", r.Code)
	}
	var count int
	_ = pool.QueryRow(context.Background(),
		"SELECT count(*) FROM contextual_likes WHERE user_id=$1", user.ID).Scan(&count)
	if count != 0 {
		t.Errorf("contextual_likes count = %d, want 0 (no open play)", count)
	}
}

func TestLikeTrack_RepeatedLike_NoDuplicate(t *testing.T) {
	h, pool := testHandlers(t)
	truncateLibrary(t, pool)
	user := seedUser(t, pool, "alice", "x", false)
	artist := seedArtist(t, pool, "X")
	album := seedAlbum(t, pool, artist.ID, "X", 1990)
	playing := seedTrack(t, pool, album.ID, artist.ID, "Playing", 1, 100_000)
	other := seedTrack(t, pool, album.ID, artist.ID, "Other", 2, 100_000)

	// Open play.
	_ = callEvents(h, user, []byte(`{"type":"play_started","track_id":"`+uuidToString(playing.ID)+`"}`))
	// First like — captures.
	_ = callLike(h, user, http.MethodPost, "/api/likes/tracks/"+uuidToString(other.ID))
	// Second like — :execrows=0, no contextual write.
	_ = callLike(h, user, http.MethodPost, "/api/likes/tracks/"+uuidToString(other.ID))

	var count int
	_ = pool.QueryRow(context.Background(),
		"SELECT count(*) FROM contextual_likes WHERE user_id=$1 AND track_id=$2", user.ID, other.ID).Scan(&count)
	if count != 1 {
		t.Errorf("contextual_likes count = %d, want 1 (no duplicate from idempotent re-like)", count)
	}
}

func TestUnlikeTrack_SoftDeletesContextualLikes(t *testing.T) {
	h, pool := testHandlers(t)
	truncateLibrary(t, pool)
	user := seedUser(t, pool, "alice", "x", false)
	artist := seedArtist(t, pool, "X")
	album := seedAlbum(t, pool, artist.ID, "X", 1990)
	playing := seedTrack(t, pool, album.ID, artist.ID, "P", 1, 100_000)
	other := seedTrack(t, pool, album.ID, artist.ID, "O", 2, 100_000)

	_ = callEvents(h, user, []byte(`{"type":"play_started","track_id":"`+uuidToString(playing.ID)+`"}`))
	_ = callLike(h, user, http.MethodPost, "/api/likes/tracks/"+uuidToString(other.ID))
	if r := callLike(h, user, http.MethodDelete, "/api/likes/tracks/"+uuidToString(other.ID)); r.Code != http.StatusNoContent {
		t.Fatalf("unlike: %d", r.Code)
	}
	// general_likes deleted.
	var glCount int
	_ = pool.QueryRow(context.Background(),
		"SELECT count(*) FROM general_likes WHERE user_id=$1 AND track_id=$2", user.ID, other.ID).Scan(&glCount)
	if glCount != 0 {
		t.Errorf("general_likes count = %d, want 0", glCount)
	}
	// contextual_likes row exists but deleted_at is set.
	var deletedAtValid bool
	_ = pool.QueryRow(context.Background(),
		"SELECT deleted_at IS NOT NULL FROM contextual_likes WHERE user_id=$1 AND track_id=$2 LIMIT 1",
		user.ID, other.ID).Scan(&deletedAtValid)
	if !deletedAtValid {
		t.Errorf("deleted_at not set after unlike")
	}
}

func TestLikeUnlikeRelike_HistoryAccumulates(t *testing.T) {
	h, pool := testHandlers(t)
	truncateLibrary(t, pool)
	user := seedUser(t, pool, "alice", "x", false)
	artist := seedArtist(t, pool, "X")
	album := seedAlbum(t, pool, artist.ID, "X", 1990)
	playing := seedTrack(t, pool, album.ID, artist.ID, "P", 1, 100_000)
	other := seedTrack(t, pool, album.ID, artist.ID, "O", 2, 100_000)

	_ = callEvents(h, user, []byte(`{"type":"play_started","track_id":"`+uuidToString(playing.ID)+`"}`))
	_ = callLike(h, user, http.MethodPost, "/api/likes/tracks/"+uuidToString(other.ID))
	_ = callLike(h, user, http.MethodDelete, "/api/likes/tracks/"+uuidToString(other.ID))
	// Re-like in same session — new row should be inserted.
	_ = callLike(h, user, http.MethodPost, "/api/likes/tracks/"+uuidToString(other.ID))

	var total, active int
	_ = pool.QueryRow(context.Background(),
		"SELECT count(*) FROM contextual_likes WHERE user_id=$1 AND track_id=$2", user.ID, other.ID).Scan(&total)
	_ = pool.QueryRow(context.Background(),
		"SELECT count(*) FROM contextual_likes WHERE user_id=$1 AND track_id=$2 AND deleted_at IS NULL",
		user.ID, other.ID).Scan(&active)
	if total != 2 {
		t.Errorf("total = %d, want 2 (history accumulates)", total)
	}
	if active != 1 {
		t.Errorf("active = %d, want 1", active)
	}
}
