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

package repocli

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

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

func (cli *Client) CheckImagesRaw(ctx context.Context, rawrepo string) ([]byte, error) {
	var err error
	res := make([]byte, 0)

	ref, err := NewReferer(rawrepo)
	if err != nil {
		return res, err
	}
	uri := ref.CheckerEP()
	req, err := http.NewRequestWithContext(ctx, http.MethodPost, uri, nil)
	if err != nil {
		return res, err
	}
	req.Header.Set("User-Agent", cli.userAgent)
	req.Header.Set("Accept", "*/*")
	resp, err := cli.httpClient.Do(req)
	if err != nil {
		return res, err
	}
	defer resp.Body.Close()
	if resp.StatusCode == http.StatusNotFound {
		return res, err
	}
	if resp.StatusCode != http.StatusOK {
		err := fmt.Errorf("Unxected response code %s", resp.Status)
		return res, err
	}

	contentLength := resp.Header.Get("Content-Length")
	if contentLength == "" {
		err = errors.New("Empty Content-Length header")
		return res, err
	}
	listSize, err := strconv.ParseInt(contentLength, 10, 64)
	if err != nil {
		return res, err
	}
	buffer := bytes.NewBuffer(nil)
	recSize, err := Copy(ctx, buffer, resp.Body)
	if listSize != recSize {
		err := fmt.Errorf("Mismatch declared and actual size")
		return res, err
	}
	res = buffer.Bytes()
	return res, err
}
