package api

import (
	"encoding/json"
	"errors"
	"net/http"

	"github.com/go-chi/chi/v5"
	"github.com/jackc/pgx/v5"
	"github.com/jackc/pgx/v5/pgtype"

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

type likedIDsResponse struct {
	TrackIDs  []string `json:"track_ids"`
	AlbumIDs  []string `json:"album_ids"`
	ArtistIDs []string `json:"artist_ids"`
}

func (h *handlers) handleLikeTrack(w http.ResponseWriter, r *http.Request) {
	user, ok := auth.UserFromContext(r.Context())
	if !ok {
		writeErr(w, http.StatusUnauthorized, "unauthorized", "authentication required")
		return
	}
	id, ok := parseUUID(chi.URLParam(r, "id"))
	if !ok {
		writeErr(w, http.StatusBadRequest, "bad_request", "invalid track id")
		return
	}
	q := dbq.New(h.pool)
	if _, err := q.GetTrackByID(r.Context(), id); err != nil {
		if errors.Is(err, pgx.ErrNoRows) {
			writeErr(w, http.StatusNotFound, "not_found", "track not found")
			return
		}
		h.logger.Error("api: like track lookup", "err", err)
		writeErr(w, http.StatusInternalServerError, "server_error", "lookup failed")
		return
	}
	rows, err := q.LikeTrack(r.Context(), dbq.LikeTrackParams{UserID: user.ID, TrackID: id})
	if err != nil {
		h.logger.Error("api: like track insert", "err", err)
		writeErr(w, http.StatusInternalServerError, "server_error", "insert failed")
		return
	}
	if rows == 1 {
		_ = playevents.CaptureContextualLikeIfPlaying(r.Context(), q, user.ID, id, h.logger)
	}
	w.WriteHeader(http.StatusNoContent)
}

func (h *handlers) handleUnlikeTrack(w http.ResponseWriter, r *http.Request) {
	user, ok := auth.UserFromContext(r.Context())
	if !ok {
		writeErr(w, http.StatusUnauthorized, "unauthorized", "authentication required")
		return
	}
	id, ok := parseUUID(chi.URLParam(r, "id"))
	if !ok {
		writeErr(w, http.StatusBadRequest, "bad_request", "invalid track id")
		return
	}
	q := dbq.New(h.pool)
	if err := q.UnlikeTrack(r.Context(), dbq.UnlikeTrackParams{UserID: user.ID, TrackID: id}); err != nil {
		h.logger.Error("api: unlike track", "err", err)
		writeErr(w, http.StatusInternalServerError, "server_error", "delete failed")
		return
	}
	if err := playevents.SoftDeleteContextualLikes(r.Context(), q, user.ID, id); err != nil {
		h.logger.Error("api: soft-delete contextual_likes", "err", err)
		// Don't fail the response — soft-delete is best-effort.
	}
	w.WriteHeader(http.StatusNoContent)
}

func (h *handlers) handleLikeAlbum(w http.ResponseWriter, r *http.Request) {
	user, ok := auth.UserFromContext(r.Context())
	if !ok {
		writeErr(w, http.StatusUnauthorized, "unauthorized", "authentication required")
		return
	}
	id, ok := parseUUID(chi.URLParam(r, "id"))
	if !ok {
		writeErr(w, http.StatusBadRequest, "bad_request", "invalid album id")
		return
	}
	q := dbq.New(h.pool)
	if _, err := q.GetAlbumByID(r.Context(), id); err != nil {
		if errors.Is(err, pgx.ErrNoRows) {
			writeErr(w, http.StatusNotFound, "not_found", "album not found")
			return
		}
		h.logger.Error("api: like album lookup", "err", err)
		writeErr(w, http.StatusInternalServerError, "server_error", "lookup failed")
		return
	}
	if err := q.LikeAlbum(r.Context(), dbq.LikeAlbumParams{UserID: user.ID, AlbumID: id}); err != nil {
		h.logger.Error("api: like album insert", "err", err)
		writeErr(w, http.StatusInternalServerError, "server_error", "insert failed")
		return
	}
	w.WriteHeader(http.StatusNoContent)
}

func (h *handlers) handleUnlikeAlbum(w http.ResponseWriter, r *http.Request) {
	user, ok := auth.UserFromContext(r.Context())
	if !ok {
		writeErr(w, http.StatusUnauthorized, "unauthorized", "authentication required")
		return
	}
	id, ok := parseUUID(chi.URLParam(r, "id"))
	if !ok {
		writeErr(w, http.StatusBadRequest, "bad_request", "invalid album id")
		return
	}
	if err := dbq.New(h.pool).UnlikeAlbum(r.Context(), dbq.UnlikeAlbumParams{UserID: user.ID, AlbumID: id}); err != nil {
		h.logger.Error("api: unlike album", "err", err)
		writeErr(w, http.StatusInternalServerError, "server_error", "delete failed")
		return
	}
	w.WriteHeader(http.StatusNoContent)
}

func (h *handlers) handleLikeArtist(w http.ResponseWriter, r *http.Request) {
	user, ok := auth.UserFromContext(r.Context())
	if !ok {
		writeErr(w, http.StatusUnauthorized, "unauthorized", "authentication required")
		return
	}
	id, ok := parseUUID(chi.URLParam(r, "id"))
	if !ok {
		writeErr(w, http.StatusBadRequest, "bad_request", "invalid artist id")
		return
	}
	q := dbq.New(h.pool)
	if _, err := q.GetArtistByID(r.Context(), id); err != nil {
		if errors.Is(err, pgx.ErrNoRows) {
			writeErr(w, http.StatusNotFound, "not_found", "artist not found")
			return
		}
		h.logger.Error("api: like artist lookup", "err", err)
		writeErr(w, http.StatusInternalServerError, "server_error", "lookup failed")
		return
	}
	if err := q.LikeArtist(r.Context(), dbq.LikeArtistParams{UserID: user.ID, ArtistID: id}); err != nil {
		h.logger.Error("api: like artist insert", "err", err)
		writeErr(w, http.StatusInternalServerError, "server_error", "insert failed")
		return
	}
	w.WriteHeader(http.StatusNoContent)
}

func (h *handlers) handleUnlikeArtist(w http.ResponseWriter, r *http.Request) {
	user, ok := auth.UserFromContext(r.Context())
	if !ok {
		writeErr(w, http.StatusUnauthorized, "unauthorized", "authentication required")
		return
	}
	id, ok := parseUUID(chi.URLParam(r, "id"))
	if !ok {
		writeErr(w, http.StatusBadRequest, "bad_request", "invalid artist id")
		return
	}
	if err := dbq.New(h.pool).UnlikeArtist(r.Context(), dbq.UnlikeArtistParams{UserID: user.ID, ArtistID: id}); err != nil {
		h.logger.Error("api: unlike artist", "err", err)
		writeErr(w, http.StatusInternalServerError, "server_error", "delete failed")
		return
	}
	w.WriteHeader(http.StatusNoContent)
}

func (h *handlers) handleListLikedTracks(w http.ResponseWriter, r *http.Request) {
	user, ok := auth.UserFromContext(r.Context())
	if !ok {
		writeErr(w, http.StatusUnauthorized, "unauthorized", "authentication required")
		return
	}
	limit, offset, err := parsePaging(r.URL.Query())
	if err != nil {
		writeErr(w, http.StatusBadRequest, "bad_request", err.Error())
		return
	}
	q := dbq.New(h.pool)
	rows, err := q.ListLikedTrackRows(r.Context(), dbq.ListLikedTrackRowsParams{
		UserID: user.ID, Limit: int32(limit), Offset: int32(offset),
	})
	if err != nil {
		h.logger.Error("api: list liked tracks", "err", err)
		writeErr(w, http.StatusInternalServerError, "server_error", "list failed")
		return
	}
	total, err := q.CountLikedTracks(r.Context(), user.ID)
	if err != nil {
		h.logger.Error("api: count liked tracks", "err", err)
		writeErr(w, http.StatusInternalServerError, "server_error", "count failed")
		return
	}
	items, err := h.resolveTrackRefs(r.Context(), q, rows)
	if err != nil {
		writeErr(w, http.StatusInternalServerError, "server_error", "list failed")
		return
	}
	writeJSON(w, http.StatusOK, Page[TrackRef]{Items: items, Total: int(total), Limit: limit, Offset: offset})
}

func (h *handlers) handleListLikedAlbums(w http.ResponseWriter, r *http.Request) {
	user, ok := auth.UserFromContext(r.Context())
	if !ok {
		writeErr(w, http.StatusUnauthorized, "unauthorized", "authentication required")
		return
	}
	limit, offset, err := parsePaging(r.URL.Query())
	if err != nil {
		writeErr(w, http.StatusBadRequest, "bad_request", err.Error())
		return
	}
	q := dbq.New(h.pool)
	rows, err := q.ListLikedAlbumRows(r.Context(), dbq.ListLikedAlbumRowsParams{
		UserID: user.ID, Limit: int32(limit), Offset: int32(offset),
	})
	if err != nil {
		h.logger.Error("api: list liked albums", "err", err)
		writeErr(w, http.StatusInternalServerError, "server_error", "list failed")
		return
	}
	total, err := q.CountLikedAlbums(r.Context(), user.ID)
	if err != nil {
		h.logger.Error("api: count liked albums", "err", err)
		writeErr(w, http.StatusInternalServerError, "server_error", "count failed")
		return
	}
	items, err := h.resolveAlbumRefs(r.Context(), q, rows)
	if err != nil {
		writeErr(w, http.StatusInternalServerError, "server_error", "list failed")
		return
	}
	writeJSON(w, http.StatusOK, Page[AlbumRef]{Items: items, Total: int(total), Limit: limit, Offset: offset})
}

func (h *handlers) handleListLikedArtists(w http.ResponseWriter, r *http.Request) {
	user, ok := auth.UserFromContext(r.Context())
	if !ok {
		writeErr(w, http.StatusUnauthorized, "unauthorized", "authentication required")
		return
	}
	limit, offset, err := parsePaging(r.URL.Query())
	if err != nil {
		writeErr(w, http.StatusBadRequest, "bad_request", err.Error())
		return
	}
	q := dbq.New(h.pool)
	rows, err := q.ListLikedArtistRows(r.Context(), dbq.ListLikedArtistRowsParams{
		UserID: user.ID, Limit: int32(limit), Offset: int32(offset),
	})
	if err != nil {
		h.logger.Error("api: list liked artists", "err", err)
		writeErr(w, http.StatusInternalServerError, "server_error", "list failed")
		return
	}
	total, err := q.CountLikedArtists(r.Context(), user.ID)
	if err != nil {
		h.logger.Error("api: count liked artists", "err", err)
		writeErr(w, http.StatusInternalServerError, "server_error", "count failed")
		return
	}
	items := make([]ArtistRef, 0, len(rows))
	for _, a := range rows {
		albums, aerr := q.ListAlbumsByArtist(r.Context(), a.ID)
		if aerr != nil {
			h.logger.Error("api: list albums for artist", "err", aerr)
			writeErr(w, http.StatusInternalServerError, "server_error", "list failed")
			return
		}
		items = append(items, artistRefFrom(a, len(albums)))
	}
	writeJSON(w, http.StatusOK, Page[ArtistRef]{Items: items, Total: int(total), Limit: limit, Offset: offset})
}

func (h *handlers) handleGetLikedIDs(w http.ResponseWriter, r *http.Request) {
	user, ok := auth.UserFromContext(r.Context())
	if !ok {
		writeErr(w, http.StatusUnauthorized, "unauthorized", "authentication required")
		return
	}
	q := dbq.New(h.pool)
	trackIDs, err := q.ListLikedTrackIDs(r.Context(), user.ID)
	if err != nil {
		h.logger.Error("api: list liked track ids", "err", err)
		writeErr(w, http.StatusInternalServerError, "server_error", "list failed")
		return
	}
	albumIDs, err := q.ListLikedAlbumIDs(r.Context(), user.ID)
	if err != nil {
		h.logger.Error("api: list liked album ids", "err", err)
		writeErr(w, http.StatusInternalServerError, "server_error", "list failed")
		return
	}
	artistIDs, err := q.ListLikedArtistIDs(r.Context(), user.ID)
	if err != nil {
		h.logger.Error("api: list liked artist ids", "err", err)
		writeErr(w, http.StatusInternalServerError, "server_error", "list failed")
		return
	}
	resp := likedIDsResponse{
		TrackIDs:  uuidsToStrings(trackIDs),
		AlbumIDs:  uuidsToStrings(albumIDs),
		ArtistIDs: uuidsToStrings(artistIDs),
	}
	writeJSON(w, http.StatusOK, resp)
}

func uuidsToStrings(ids []pgtype.UUID) []string {
	out := make([]string, 0, len(ids))
	for _, id := range ids {
		out = append(out, uuidToString(id))
	}
	return out
}

// Compile-time references so the json import is always live even when
// no handler in this file decodes a body.
var _ = json.Marshal
