package bunny

import (
	"context"
	"fmt"
	"io"
	"net/http"
	"strings"
)

// Delete removes a single object with a raw DELETE, applying the shared retry
// policy.
func (api *API) Delete(ctx context.Context, path string) error {
	return api.delete(ctx, api.url(path))
}

// DeleteDir removes a directory. Bunny's storage endpoints identify a directory
// by a trailing slash on the URL (the same quirk listDir relies on), so we
// append it here rather than leak the convention to callers. The delete is
// recursive.
//
// CAUTION: The delete is recursive AND prune decides emptiness from the
// pre-delete listing snapshot. If another actor uploads a file under this directory
// between the snapshot and this call, the recursive delete will remove it.
func (api *API) DeleteDir(ctx context.Context, path string) error {
	u := api.url(path)
	if !strings.HasSuffix(u, "/") {
		u += "/"
	}
	return api.delete(ctx, u)
}

func (api *API) delete(ctx context.Context, u string) error {
	req, err := http.NewRequestWithContext(ctx, http.MethodDelete, u, nil)
	if err != nil {
		return fmt.Errorf("build request: %w", err)
	}

	resp, err := api.do(ctx, req)
	if err != nil {
		return err
	}
	io.Copy(io.Discard, resp.Body)
	resp.Body.Close()
	return nil
}
