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

package repocli

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

func (cli *Client) BlobExists(ctx context.Context, rawrepo string, digest string) (bool, int64, error) {
	var err error
	var exist bool
	var size int64

	ref, err := NewReferer(rawrepo)
	if err != nil {
		return exist, size, err
	}
	uri := ref.BlobEP(digest)
	req, err := http.NewRequestWithContext(ctx, http.MethodHead, uri, nil)
	if err != nil {
		return exist, size, err
	}
	req.Header.Set("User-Agent", cli.userAgent)
	req.Header.Set("Accept", "*/*")

	resp, err := cli.httpClient.Do(req)
	if err != nil {
		return exist, size, err
	}
	defer resp.Body.Close()

	if resp.StatusCode == http.StatusNotFound {
		return exist, size, err
	}
	if resp.StatusCode != http.StatusOK {
		err := fmt.Errorf("Unxected response code %s", resp.Status)
		return exist, size, err
	}
	contentLength := resp.Header.Get("Content-Length")
	size, err = strconv.ParseInt(contentLength, 10, 64)
	if err != nil {
		return exist, size, err
	}

	exist = true
	return exist, size, err
}
