package services

import (
	"encoding/json"
	"fmt"
	"io"
	"log"
	"messageService/internal/app/models"
	"net/http"
	"time"
)

type StreamClient interface {
	GetStreamTitleByID(streamId uint) (string, error)
}

type streamClient struct {
	BaseURL string
	Timeout time.Duration
}

func NewStreamClient(baseURL string, timeout time.Duration) StreamClient {
	return &streamClient{
		BaseURL: baseURL,
		Timeout: timeout,
	}
}

func (c *streamClient) GetStreamTitleByID(streamID uint) (string, error) {
	client := &http.Client{Timeout: c.Timeout}
	url := fmt.Sprintf("%s/streams/%d", c.BaseURL, streamID)
	log.Printf(url)

	resp, err := client.Get(url)
	if err != nil {
		return "", err
	}
	defer func(Body io.ReadCloser) {
		err := Body.Close()
		if err != nil {

		}
	}(resp.Body)

	log.Printf("Response Status: %s", resp.Status)
	body, _ := io.ReadAll(resp.Body)
	log.Printf("Response Body: %s", body)

	if resp.StatusCode != http.StatusOK {
		return "", fmt.Errorf("failed to get stream title: %s", resp.Status)
	}

	var stream models.StreamResponse
	if err := json.Unmarshal(body, &stream); err != nil {
		log.Printf("Unmarshal error: %s", err)
		return "", err
	}

	log.Printf("Name: %s", stream.Title)

	return stream.Title, nil
}
