package lidarr

import (
	"context"
	"fmt"
	"net/http"
	"net/url"
	"strconv"
	"strings"
)

// del is the shared DELETE helper. Mirrors get()/post() in client.go: builds
// the URL inline, sets the API key, maps status codes to typed errors. The
// caller is responsible for closing the returned body.
func (c *Client) del(ctx context.Context, path string, q url.Values) (*http.Response, error) {
	u, err := url.Parse(c.BaseURL)
	if err != nil {
		return nil, fmt.Errorf("%w: %v", ErrUnreachable, err)
	}
	u.Path = strings.TrimRight(u.Path, "/") + path
	if q != nil {
		u.RawQuery = q.Encode()
	}
	req, err := http.NewRequestWithContext(ctx, http.MethodDelete, u.String(), nil)
	if err != nil {
		return nil, err
	}
	req.Header.Set("X-Api-Key", c.APIKey)

	resp, err := c.HTTP.Do(req)
	if err != nil {
		return nil, fmt.Errorf("%w: %v", ErrUnreachable, err)
	}
	if resp.StatusCode == http.StatusUnauthorized || resp.StatusCode == http.StatusForbidden {
		_ = resp.Body.Close()
		return nil, ErrAuthFailed
	}
	if resp.StatusCode >= 500 {
		_ = resp.Body.Close()
		return nil, ErrServerError
	}
	if resp.StatusCode >= 400 {
		_ = resp.Body.Close()
		return nil, ErrLookupFailed
	}
	return resp, nil
}

// DeleteAlbum removes an album from Lidarr's library.
//   - deleteFiles=true also removes the audio files from disk.
//   - addImportListExclusion=true tells Lidarr to never re-add this album
//     via import-list scans.
//
// M5b's admin "delete via Lidarr" action always passes both `true`.
func (c *Client) DeleteAlbum(ctx context.Context, lidarrAlbumID int, deleteFiles, addImportListExclusion bool) error {
	if lidarrAlbumID == 0 {
		return fmt.Errorf("lidarr: zero album id")
	}
	q := url.Values{
		"deleteFiles":            []string{strconv.FormatBool(deleteFiles)},
		"addImportListExclusion": []string{strconv.FormatBool(addImportListExclusion)},
	}
	resp, err := c.del(ctx, "/api/v1/album/"+strconv.Itoa(lidarrAlbumID), q)
	if err != nil {
		return err
	}
	_ = resp.Body.Close()
	return nil
}
