package repocli

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

func (cli *Client) GetUpload(ctx context.Context, rawrepo string) (string, string, error) {
	var err error
	var loc string
	var id string

	ref, err := NewReferer(rawrepo)
	if err != nil {
		return id, loc, err
	}
	uri := ref.UploadEP()

	req, err := http.NewRequestWithContext(ctx, http.MethodPost, uri, nil)
	if err != nil {
		return id, loc, err
	}
	req.Header.Set("User-Agent", cli.userAgent)
	req.Header.Set("Accept", "*/*")
	resp, err := cli.httpClient.Do(req)
	if err != nil {
		return id, loc, err
	}
	defer resp.Body.Close()

	if resp.StatusCode != http.StatusAccepted {
		err := fmt.Errorf("Unxected response code %s", resp.Status)
		return id, loc, err
	}
	loc = resp.Header.Get("Location")
	if loc == "" {
		err := fmt.Errorf("Empty location declaration")
		return id, loc, err
	}
	id = resp.Header.Get("Docker-Upload-UUID")
	if id == "" {
		err := fmt.Errorf("Empty Docker-Upload-UUID declaration")
		return id, loc, err
	}
	return id, loc, err
}
