/*
 * 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 (
	"crypto/tls"
	"net/http"
	"net/url"
	"path"
	"strings"
)

func makeHTTPClient() *http.Client {
	transport := &http.Transport{
		TLSClientConfig: &tls.Config{
			InsecureSkipVerify: true,
		},
	}
	client := &http.Client{
		Transport: transport,
	}
	return client
}

func convertFileURI(fileuri string) (string, error) {
	var err error
	var res string
	uri, err := url.Parse(fileuri)
	if err != nil {
		return res, err
	}
	const fileAPI = "/v3/api/file/"
	uri.Path, err = url.JoinPath(fileAPI, uri.Path)
	if err != nil {
		return res, err
	}

	res = uri.String()
	return res, err
}

func convertFilesURI(fileuri string) (string, error) {
	var err error
	var res string
	uri, err := url.Parse(fileuri)
	const filesAPI = "/v3/api/files/"
	uri.Path, err = url.JoinPath(filesAPI, uri.Path)
	if err != nil {
		return res, err
	}
	res = uri.String()
	return res, err
}

func convertCollectionsURI(fileuri string) (string, error) {
	var err error
	var res string
	uri, err := url.Parse(fileuri)
	const prefixAPI = "/v3/api/collections/"
	uri.Path, err = url.JoinPath(prefixAPI, uri.Path)
	if err != nil {
		return res, err
	}
	res = uri.String()
	return res, err
}

func convertCollectionURI(fileuri string) (string, error) {
	var err error
	var res string
	uri, err := url.Parse(fileuri)
	const prefixAPI = "/v3/api/collection/"
	uri.Path, err = url.JoinPath(prefixAPI, uri.Path)
	if err != nil {
		return res, err
	}
	res = uri.String()
	return res, err
}

func repackServiceURI(fileuri string) (string, string, string, error) {
	var err error
	var res, username, password string
	if !strings.Contains(fileuri, "://") {
		fileuri = "https://" + fileuri
	}
	uri, err := url.Parse(fileuri)
	if err != nil {
		return res, username, password, err
	}
	uri.Path = path.Clean(uri.Path)
	if uri.User != nil {
		username = uri.User.Username()
		password, _ = uri.User.Password()
	}
	uri.User = nil
	//uri.Scheme = "https"
	res = uri.String()
	return res, username, password, err
}
