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

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

func (cli *Client) GetFile(ctx context.Context, rawpath string, writer io.Writer) (bool, error) {
	var err error
	var exist bool

	ref, err := ParsePath(rawpath)
	if err != nil {
		return exist, err
	}
	uri := ref.FileEP()

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

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

	recSize, err := Copy(ctx, writer, resp.Body)
	if blobSize != recSize {
		err := fmt.Errorf("Mismatch declared and actual body size: %d and %d", blobSize, recSize)
		return exist, err
	}
	exist = true
	return exist, err
}
