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

package repocli

import (
	"bytes"
	"context"
	"encoding/json"
	"errors"
	"fmt"
	"net/http"
	"strconv"
)

func (cli *Client) GetCatalog(ctx context.Context, rawrepo string) ([]string, error) {
	var err error
	list := make([]string, 0)
	catdata, err := cli.GetRawCatalog(ctx, rawrepo)
	if err != nil {
		return list, err
	}
	err = json.Unmarshal(catdata, &list)
	if err != nil {
		return list, err
	}
	return list, err
}

func (cli *Client) GetRawCatalog(ctx context.Context, rawrepo string) ([]byte, error) {
	var err error
	var list []byte

	ref, err := NewReferer(rawrepo)
	if err != nil {
		return list, err
	}
	uri := ref.CatalogEP()

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

	if resp.StatusCode == http.StatusNotFound {
		return list, err
	}
	if resp.StatusCode != http.StatusOK {
		err := fmt.Errorf("Unxected response code %s", resp.Status)
		return list, err
	}
	contentLength := resp.Header.Get("Content-Length")
	if contentLength == "" {
		err = errors.New("Empty Content-Length header")
		return list, err
	}
	listSize, err := strconv.ParseInt(contentLength, 10, 64)
	if err != nil {
		return list, err
	}
	buffer := bytes.NewBuffer(nil)
	recSize, err := Copy(ctx, buffer, resp.Body)
	if listSize != recSize {
		err := fmt.Errorf("Mismatch declared and actual size")
		return list, err
	}
	list = buffer.Bytes()
	return list, err
}
