/*
 * Copyright 2026 Oleg Borodin <onborodin@gmail.com>
 *
 * This work is published and licensed under a Creative Commons
 * Attribution-NonCommercial-NoDerivatives 4.0 International License.
 *
 * Distribution of this work is permitted, but commercial use and
 * modifications are strictly prohibited.
 */
package client

import (
	"bytes"
	"context"
	"crypto/tls"
	"fmt"
	"io"
	"net/http"
	"net/url"
	"strings"

	"mstore/pkg/auxhttp"
)

func setApiPath(base, apipath string) (string, error) {
	var res string
	if !strings.Contains(base, "://") {
		base = "https://" + base
	}
	uri, err := url.Parse(base)
	if err != nil {
		return res, err
	}
	uri.Path = "/"
	uri.Path, err = url.JoinPath(uri.Path, apipath)
	if err != nil {
		return res, err
	}
	res = uri.String()
	return res, nil

}

func doHTTPCall(ctx context.Context, apiuri string, reqBytes []byte) ([]byte, error) {
	var err error
	respBytes := make([]byte, 0)

	apiuri, username, password, err := repackServiceURI(apiuri)
	if err != nil {
		return respBytes, err
	}
	reqBuffer := bytes.NewBuffer(reqBytes)
	httpReq, err := http.NewRequestWithContext(ctx, http.MethodPost, apiuri, reqBuffer)
	if err != nil {
		return respBytes, err
	}
	httpReq.Header.Set("Content-Type", "application/json")
	if username != "" && password != "" {
		basicHeader := auxhttp.EncodeBasicAuth(username, password)
		httpReq.Header.Add("Authorization", basicHeader)
	}
	transport := &http.Transport{
		TLSClientConfig: &tls.Config{InsecureSkipVerify: true},
	}
	httpClient := &http.Client{
		Transport: transport,
	}
	httpResp, err := httpClient.Do(httpReq)
	if err != nil {
		return respBytes, err
	}
	defer httpResp.Body.Close()
	if httpResp.StatusCode != http.StatusOK {
		err := fmt.Errorf("Wrong StatusCode header: %s", httpResp.Status)
		return respBytes, err
	}
	respBuffer := bytes.NewBuffer(nil)
	_, err = io.Copy(respBuffer, httpResp.Body)
	if err != nil {
		return respBytes, err
	}
	respBytes = respBuffer.Bytes()
	return respBytes, err
}
