package services

import (
	"bytes"
	"context"
	"encoding/json"
	"fmt"
	"github.com/google/uuid" // Added import for uuid
	"net/http"
	"time"

	"go.uber.org/zap"
)

type StreamService struct {
	baseURL string
	client  *http.Client
	logger  *zap.Logger
}

func NewStreamService(baseURL string, logger *zap.Logger) *StreamService {
	if logger == nil {
		logger = zap.NewNop()
	}
	return &StreamService{
		baseURL: baseURL,
		client:  &http.Client{Timeout: 10 * time.Second},
		logger:  logger,
	}
}

type TranscodeRequest struct {
	TrackID  string `json:"track_id"`
	FilePath string `json:"file_path"`
}

func (s *StreamService) StartProcessing(ctx context.Context, trackID uuid.UUID, filePath string) error { // Changed trackID to uuid.UUID
	url := fmt.Sprintf("%s/internal/jobs/transcode", s.baseURL)
	reqBody := TranscodeRequest{
		TrackID:  trackID.String(), // Converted uuid.UUID to string
		FilePath: filePath,
	}

	jsonBody, err := json.Marshal(reqBody)
	if err != nil {
		return fmt.Errorf("failed to marshal request: %w", err)
	}

	req, err := http.NewRequestWithContext(ctx, "POST", url, bytes.NewBuffer(jsonBody))
	if err != nil {
		return fmt.Errorf("failed to create request: %w", err)
	}
	req.Header.Set("Content-Type", "application/json")

	resp, err := s.client.Do(req)
	if err != nil {
		return fmt.Errorf("failed to send request: %w", err)
	}
	defer resp.Body.Close()

	if resp.StatusCode != http.StatusOK {
		return fmt.Errorf("stream server returned status: %d", resp.StatusCode)
	}

	s.logger.Info("Started processing for track", zap.Any("track_id", trackID)) // Changed to zap.Any for uuid.UUID
	return nil
}
