package handlers

import (
	"bytes"
	"encoding/json"
	"github.com/bwmarrin/discordgo"
	"kleincordBot/services"
	"log"
	"net/http"
	"net/http/httputil"
	"strings"
)

func HttpCommand(data discordgo.ApplicationCommandInteractionData, s *discordgo.Session, i *discordgo.InteractionCreate) {

	var requestType string
	var requestUrl string
	var requestBody string
	var err error
	var response *http.Response
	var responsColor int

	for _, option := range data.Options {
		switch option.Name {
		case "type":
			requestType = option.Value.(string)
		case "url":
			requestUrl = option.Value.(string)
		case "body":
			requestBody = option.Value.(string)
		}
	}
	body := strings.Split(requestBody, ",")
	bodyMap := make(map[string]any)
	for _, entry := range body {
		KeyValPair := strings.Split(entry, ":")
		if len(KeyValPair) < 2 {
			break
		}
		bodyMap[KeyValPair[0]] = KeyValPair[1]
	}
	postBody, _ := json.Marshal(bodyMap)
	responseBody := bytes.NewBuffer(postBody)

	switch requestType {
	case "post":
		response, err = http.Post(requestUrl, "application/json", responseBody)
		if err != nil {
			log.Fatalf("An Error Occured %v", err)
		}
	case "get":
		response, err = http.Get(requestUrl)
		if err != nil {
			log.Fatalf("An Error Occured %v", err)
		}
	default:
		return //todo add handeling later
	}
	byts, _ := httputil.DumpResponse(response, true)

	switch statusCode := response.StatusCode; {
	case statusCode >= 200 && statusCode < 300:
		responsColor = 0x008000
	case statusCode >= 300 && statusCode < 400:
		responsColor = 0xffff00
	case statusCode >= 400 && statusCode < 500:
		responsColor = 0xffa500
	case statusCode >= 500 && statusCode < 600:
		responsColor = 0xff0000
	}

	err = s.InteractionRespond(
		i.Interaction,
		&discordgo.InteractionResponse{
			Type: discordgo.InteractionResponseChannelMessageWithSource,
			Data: &discordgo.InteractionResponseData{
				Embeds: []*discordgo.MessageEmbed{
					{
						Title: response.Status,
						Color: responsColor,
						Fields: []*discordgo.MessageEmbedField{
							{
								Value: string(byts),
							},
						},
						Type: discordgo.EmbedTypeArticle,
					},
				},
			},
		},
	)
	if err != nil {
		services.HandleError(err, s)
	}
}
