package api

import (
	"errors"
	"net/http"

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

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

// handleGetTrack implements GET /api/tracks/{id}. Resolves parent album +
// artist names so the response is self-contained — clients should not need
// a follow-up request to render a track outside an album view.
func (h *handlers) handleGetTrack(w http.ResponseWriter, r *http.Request) {
	id, ok := parseUUID(chi.URLParam(r, "id"))
	if !ok {
		writeErr(w, http.StatusBadRequest, "bad_request", "invalid track id")
		return
	}
	q := dbq.New(h.pool)
	track, err := q.GetTrackByID(r.Context(), id)
	if err != nil {
		if errors.Is(err, pgx.ErrNoRows) {
			writeErr(w, http.StatusNotFound, "not_found", "track not found")
			return
		}
		h.logger.Error("api: get track failed", "err", err)
		writeErr(w, http.StatusInternalServerError, "server_error", "lookup failed")
		return
	}
	album, err := q.GetAlbumByID(r.Context(), track.AlbumID)
	if err != nil {
		h.logger.Error("api: get track album failed", "err", err)
		writeErr(w, http.StatusInternalServerError, "server_error", "lookup failed")
		return
	}
	artist, err := q.GetArtistByID(r.Context(), track.ArtistID)
	if err != nil {
		h.logger.Error("api: get track artist failed", "err", err)
		writeErr(w, http.StatusInternalServerError, "server_error", "lookup failed")
		return
	}
	writeJSON(w, http.StatusOK, trackRefFrom(track, album.Title, artist.Name))
}

// handleGetAlbum implements GET /api/albums/{id}. Returns the album plus its
// tracks (ordered by disc/track number via the underlying query) with
// duration summed from the track list — keeps one source of truth.
func (h *handlers) handleGetAlbum(w http.ResponseWriter, r *http.Request) {
	id, ok := parseUUID(chi.URLParam(r, "id"))
	if !ok {
		writeErr(w, http.StatusBadRequest, "bad_request", "invalid album id")
		return
	}
	q := dbq.New(h.pool)
	album, err := q.GetAlbumByID(r.Context(), id)
	if err != nil {
		if errors.Is(err, pgx.ErrNoRows) {
			writeErr(w, http.StatusNotFound, "not_found", "album not found")
			return
		}
		h.logger.Error("api: get album failed", "err", err)
		writeErr(w, http.StatusInternalServerError, "server_error", "lookup failed")
		return
	}
	artist, err := q.GetArtistByID(r.Context(), album.ArtistID)
	if err != nil {
		h.logger.Error("api: get album artist failed", "err", err)
		writeErr(w, http.StatusInternalServerError, "server_error", "lookup failed")
		return
	}
	tracks, err := q.ListTracksByAlbum(r.Context(), id)
	if err != nil {
		h.logger.Error("api: list tracks failed", "err", err)
		writeErr(w, http.StatusInternalServerError, "server_error", "lookup failed")
		return
	}
	refs := make([]TrackRef, 0, len(tracks))
	durSec := 0
	for _, t := range tracks {
		ref := trackRefFrom(t, album.Title, artist.Name)
		refs = append(refs, ref)
		durSec += ref.DurationSec
	}
	detail := AlbumDetail{
		AlbumRef: albumRefFrom(album, artist.Name, len(tracks), durSec),
		Tracks:   refs,
	}
	writeJSON(w, http.StatusOK, detail)
}

// handleGetArtist implements GET /api/artists/{id}. Returns artist + albums;
// each album carries its own track_count (one count query per album, same
// pattern as subsonic). At M1 sizes (albums-per-artist << 100) this is fine.
func (h *handlers) handleGetArtist(w http.ResponseWriter, r *http.Request) {
	id, ok := parseUUID(chi.URLParam(r, "id"))
	if !ok {
		writeErr(w, http.StatusBadRequest, "bad_request", "invalid artist id")
		return
	}
	q := dbq.New(h.pool)
	artist, err := q.GetArtistByID(r.Context(), id)
	if err != nil {
		if errors.Is(err, pgx.ErrNoRows) {
			writeErr(w, http.StatusNotFound, "not_found", "artist not found")
			return
		}
		h.logger.Error("api: get artist failed", "err", err)
		writeErr(w, http.StatusInternalServerError, "server_error", "lookup failed")
		return
	}
	albums, err := q.ListAlbumsByArtist(r.Context(), id)
	if err != nil {
		h.logger.Error("api: list albums by artist failed", "err", err)
		writeErr(w, http.StatusInternalServerError, "server_error", "lookup failed")
		return
	}
	refs := make([]AlbumRef, 0, len(albums))
	for _, a := range albums {
		count, cerr := q.CountTracksByAlbum(r.Context(), a.ID)
		if cerr != nil {
			h.logger.Error("api: count tracks failed", "err", cerr)
			writeErr(w, http.StatusInternalServerError, "server_error", "lookup failed")
			return
		}
		// durationSec=0: not aggregated for nested album lists per spec data flow.
		refs = append(refs, albumRefFrom(a, artist.Name, int(count), 0))
	}
	detail := ArtistDetail{
		ArtistRef: artistRefFrom(artist, len(albums)),
		Albums:    refs,
	}
	writeJSON(w, http.StatusOK, detail)
}

// handleListArtists implements GET /api/artists with two sort modes
// (alpha|newest) and enveloped pagination. album_count per artist is
// computed via an N+1 — acceptable at limit=200.
func (h *handlers) handleListArtists(w http.ResponseWriter, r *http.Request) {
	sort := r.URL.Query().Get("sort")
	if sort == "" {
		sort = "alpha"
	}
	if sort != "alpha" && sort != "newest" {
		writeErr(w, http.StatusBadRequest, "bad_request", "sort must be alpha or newest")
		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)
	var artists []dbq.Artist
	switch sort {
	case "newest":
		artists, err = q.ListArtistsNewest(r.Context(), dbq.ListArtistsNewestParams{
			Limit: int32(limit), Offset: int32(offset),
		})
	default: // alpha
		artists, err = q.ListArtistsAlpha(r.Context(), dbq.ListArtistsAlphaParams{
			Limit: int32(limit), Offset: int32(offset),
		})
	}
	if err != nil {
		h.logger.Error("api: list artists failed", "err", err)
		writeErr(w, http.StatusInternalServerError, "server_error", "lookup failed")
		return
	}
	total, err := q.CountArtists(r.Context())
	if err != nil {
		h.logger.Error("api: count artists failed", "err", err)
		writeErr(w, http.StatusInternalServerError, "server_error", "count failed")
		return
	}

	items := make([]ArtistRef, 0, len(artists))
	for _, a := range artists {
		albums, aerr := q.ListAlbumsByArtist(r.Context(), a.ID)
		if aerr != nil {
			h.logger.Error("api: list albums for artist failed", "err", aerr)
			writeErr(w, http.StatusInternalServerError, "server_error", "lookup failed")
			return
		}
		items = append(items, artistRefFrom(a, len(albums)))
	}
	writeJSON(w, http.StatusOK, Page[ArtistRef]{
		Items:  items,
		Total:  int(total),
		Limit:  limit,
		Offset: offset,
	})
}
