/*
  * Copyright 2026 Oleg Borodin <onborodin@gmail.com>
 *
 *
*/

package repocli

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

func (cli *Client) PutUpload(ctx context.Context, rawrepo string, src io.Reader, id, digest string, size int64) (string, error) {
	var err error
	var bloc string

	ref, err := NewReferer(rawrepo)
	if err != nil {
		return bloc, err
	}
	uri, err := ref.PutEP(id, digest)
	if err != nil {
		return bloc, err
	}
	req, err := http.NewRequestWithContext(ctx, http.MethodPut, uri, src)
	if err != nil {
		return bloc, err
	}
	req.Header.Set("User-Agent", cli.userAgent)
	req.Header.Set("Content-Type", "application/octet-stream")
	req.Header.Set("Content-Length", strconv.FormatInt(size, 10))
	resp, err := cli.httpClient.Do(req)
	if err != nil {
		return bloc, err
	}
	resp.Body.Close()
	if resp.StatusCode != http.StatusCreated {
		err = fmt.Errorf("Upload not accepted, code %d", resp.StatusCode)
		return bloc, err
	}
	bloc = resp.Header.Get("Location")
	if bloc == "" {
		err := fmt.Errorf("Empty blob location declaration")
		return bloc, err
	}
	return bloc, err
}
