/*
 * 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 (
	"context"
	"crypto/tls"
	"net/http"
	"net/url"
	"time"

	"mstore/pkg/auxhttp"
)

func convertServiceURI(ref string) (string, error) {
	var err error
	var res string
	const serviceAPI = "/v3/api/service/"
	const serviceScheme = "https"
	uri, err := url.Parse(ref)
	if err != nil {
		return res, err
	}
	uri.Path, err = url.JoinPath(serviceAPI, uri.Path)
	if err != nil {
		return res, err
	}
	uri.Scheme = serviceScheme
	res = uri.String()
	return res, err
}

func (cli *Client) ServiceHello(ctx context.Context, serviceuri string, timeout time.Duration) (bool, error) {
	var res bool
	var err error
	ctx, _ = context.WithTimeout(ctx, timeout)

	serviceuri, username, password, err := repackServiceURI(serviceuri)
	if err != nil {
		return res, err
	}
	serviceuri, err = convertServiceURI(serviceuri)

	if err != nil {
		return res, err
	}
	req, err := http.NewRequestWithContext(ctx, http.MethodGet, serviceuri, nil)
	if err != nil {
		return res, err
	}
	if username != "" && password != "" {
		basic := auxhttp.EncodeBasicAuth(username, password)
		req.Header.Add("Authorization", basic)
	}
	transport := &http.Transport{
		TLSClientConfig: &tls.Config{
			InsecureSkipVerify: true,
		},
	}
	client := &http.Client{
		Transport: transport,
	}
	resp, err := client.Do(req)
	if err != nil {
		return res, err
	}
	defer resp.Body.Close()
	if resp.StatusCode == http.StatusOK {
		res = true
	}
	return res, err
}
