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

package repocli

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

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

	ref, err := NewReferer(rawrepo)
	if err != nil {
		return exist, mime, size, csum, err
	}
	uri := ref.ManifestEP()

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

	if resp.StatusCode == http.StatusNotFound {
		return exist, mime, size, csum, err
	}
	if resp.StatusCode != http.StatusOK {
		err := fmt.Errorf("Unxected response code %s", resp.Status)
		return exist, mime, size, csum, err
	}
	contentLength := resp.Header.Get("Content-Length")
	size, err = strconv.ParseInt(contentLength, 10, 64)
	if err != nil {
		return exist, mime, size, csum, err
	}
	mime = resp.Header.Get("Content-Type")
	if mime == "" {
		err := fmt.Errorf("Empty MIME type declaration")
		return exist, mime, size, csum, err
	}
	csum = resp.Header.Get("Docker-Content-Digest")
	if csum == "" {
		err := fmt.Errorf("Empty digest declaration")
		return exist, mime, size, csum, err
	}

	exist = true
	return exist, mime, size, csum, err
}
