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

package repocli

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

	ocidigest "github.com/opencontainers/go-digest"
)

func (cli *Client) PutManifest(ctx context.Context, rawref string, man []byte, mime string) error {
	var err error

	ref, err := NewReferer(rawref)
	if err != nil {
		return err
	}
	uri := ref.ManifestEP()

	reader := bytes.NewReader(man)
	req, err := http.NewRequestWithContext(ctx, http.MethodPut, uri, reader)
	if err != nil {
		return err
	}
	req.Header.Set("User-Agent", cli.userAgent)
	// TODO: digest
	digestobj := ocidigest.NewDigestFromBytes(ocidigest.SHA256, man)
	req.Header.Set("Docker-Content-Digest", digestobj.Encoded())
	req.Header.Set("Content-Type", mime)
	resp, err := cli.httpClient.Do(req)
	if err != nil {
		return err
	}
	resp.Body.Close()
	if resp.StatusCode != http.StatusAccepted && resp.StatusCode != http.StatusCreated {
		err = fmt.Errorf("Manifest not accepted, code %d", resp.StatusCode)
		return err
	}
	loc := resp.Header.Get("Location")
	if loc == "" {
		err := fmt.Errorf("Empty manifest location declaration")
		return err
	}
	return err
}
