package lidarr

import (
	"context"
	"encoding/json"
	"fmt"
	"net/url"
)

// LookupArtistByMBID returns the artist Lidarr has indexed under that
// MBID. Returns ErrNotFound if Lidarr returns an empty array.
func (c *Client) LookupArtistByMBID(ctx context.Context, mbid string) (LidarrArtist, error) {
	if mbid == "" {
		return LidarrArtist{}, fmt.Errorf("lidarr: empty mbid")
	}
	q := url.Values{"mbId": []string{mbid}}
	resp, err := c.get(ctx, "/api/v1/artist", q)
	if err != nil {
		return LidarrArtist{}, err
	}
	defer func() { _ = resp.Body.Close() }()

	var rows []LidarrArtist
	if err := json.NewDecoder(resp.Body).Decode(&rows); err != nil {
		return LidarrArtist{}, fmt.Errorf("%w: decode artist: %v", ErrInvalidPayload, err)
	}
	if len(rows) == 0 {
		return LidarrArtist{}, ErrNotFound
	}
	return rows[0], nil
}

// LookupAlbumByMBID returns the album Lidarr has indexed under that
// MBID. Returns ErrNotFound on empty result.
func (c *Client) LookupAlbumByMBID(ctx context.Context, mbid string) (LidarrAlbum, error) {
	if mbid == "" {
		return LidarrAlbum{}, fmt.Errorf("lidarr: empty mbid")
	}
	q := url.Values{"foreignAlbumId": []string{mbid}}
	resp, err := c.get(ctx, "/api/v1/album", q)
	if err != nil {
		return LidarrAlbum{}, err
	}
	defer func() { _ = resp.Body.Close() }()

	var rows []LidarrAlbum
	if err := json.NewDecoder(resp.Body).Decode(&rows); err != nil {
		return LidarrAlbum{}, fmt.Errorf("%w: decode album: %v", ErrInvalidPayload, err)
	}
	if len(rows) == 0 {
		return LidarrAlbum{}, ErrNotFound
	}
	return rows[0], nil
}
