package studio_api

import (
	"bytes"
	"encoding/json"
	"fmt"
	"io"
	"net/http"
	"os"
)

func SendStudioApiRequest(authToken string, method string, path string, params map[string]interface{}) (string, error) {
	urlBase := "studio-api.suno-studio-api.local"
	if os.Getenv("REDIS_URL") == "redis://localhost:6379" {
		urlBase = "localhost:8000"
	}

	url := fmt.Sprintf("http://%s%s", urlBase, path)
	// Marshal the Params as payload into JSON
	jsonPayload, err := json.Marshal(params)
	if err != nil {
		return "", err
	}

	req, err := http.NewRequest(method, url, bytes.NewBuffer(jsonPayload))
	if err != nil {
		return "", err
	}
	req.Header.Set("Authorization", "Bearer "+authToken)
	req.Header.Set("Content-Type", "application/json")

	client := &http.Client{}
	resp, err := client.Do(req)
	if err != nil {
		return "", err
	}
	defer resp.Body.Close()

	if resp.StatusCode != http.StatusOK {
		return "", fmt.Errorf("failed to make api call: %s", resp.Status)
	}

	body, err := io.ReadAll(resp.Body)
	if err != nil {
		return "", err
	}

	var jsonResponse map[string]interface{}
	if err := json.Unmarshal(body, &jsonResponse); err != nil {
		return "", err
	}

	responseMessage, err := json.Marshal(jsonResponse)
	if err != nil {
		return "", err
	}

	return string(responseMessage), nil
}
