package utils

import (
	"encoding/xml"
	"fmt"
	"io"
	"log"
	"net/http"
	"os"
	"reflect"
	"strings"
)

func Ptr[T any](v T) *T { return &v }

func MakeUppercase(s string) string {
	if s != "" && reflect.TypeOf(s).Kind() == reflect.String && len(s) > 0 {
		return strings.ToUpper(string(s[0])) + s[1:]
	}
	return ""
}

func fetchXML(url string) ([]byte, error) {
	resp, err := http.Get(url)
	if err != nil {
		return []byte{}, fmt.Errorf("GET error: %v", err)
	}
	defer resp.Body.Close()

	if resp.StatusCode != http.StatusOK {
		return []byte{}, fmt.Errorf("status error: %v", resp.StatusCode)
	}

	data, err := io.ReadAll(resp.Body)
	if err != nil {
		return []byte{}, fmt.Errorf("read body: %v", err)
	}

	return data, nil
}

func GetDataXML[T any](url string) T {
	xmlBytes, err := fetchXML(url)
	if err != nil {
		log.Fatalf("Failed to get XML: %v", err)
		panic(err)
	}
	var result T
	err = xml.Unmarshal(xmlBytes, &result)
	if err != nil {
		log.Fatalf("Failed to unmarshal XML: %v", err)
		panic(err)
	}
	return result
}

func SafeRemoveAll(path string) error {
	err := os.RemoveAll(path)
	if err != nil {
		if os.IsNotExist(err) {
			return nil
		}
		return err
	}
	return nil
}

func GetStringValue(strPtr *string) string {
	if strPtr != nil {
		return *strPtr
	}
	return ""
}
func RemoveWhitespace(str string) string {
	return strings.ReplaceAll(str, " ", "")
}

func CommaToDot(str *string) *string {
	if str != nil {
		result := strings.ReplaceAll(*str, ",", ".")
		return &result
	}
	return nil
}
