package services

import (
	"context"
	"encoding/json"
	"net/http"
	"net/http/httptest"
	"strings"
	"testing"

	"github.com/google/uuid"

	"github.com/stretchr/testify/assert"
	"go.uber.org/zap"
)

func TestStreamService_StartProcessing(t *testing.T) {
	// Setup mock server
	server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
		assert.Equal(t, "/internal/jobs/transcode", r.URL.Path)
		assert.Equal(t, "POST", r.Method)
		assert.Equal(t, "application/json", r.Header.Get("Content-Type"))

		var req TranscodeRequest
		err := json.NewDecoder(r.Body).Decode(&req)
		assert.NoError(t, err)
		// We can't easily assert the random UUID string here unless we capture it from the request in the test setup
		// However, we can assert it's a valid UUID
		_, err = uuid.Parse(req.TrackID)
		assert.NoError(t, err, "TrackID should be a valid UUID")
		assert.Equal(t, "/path/to/file", req.FilePath)

		w.WriteHeader(http.StatusOK)
	}))
	defer server.Close()

	logger := zap.NewNop()
	service := NewStreamService(server.URL, logger)

	trackID := uuid.New()
	err := service.StartProcessing(context.Background(), trackID, "/path/to/file")
	assert.NoError(t, err)
}

func TestStreamService_StartProcessing_Error(t *testing.T) {
	// Setup mock server that returns error
	server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
		w.WriteHeader(http.StatusInternalServerError)
	}))
	defer server.Close()

	logger := zap.NewNop()
	service := NewStreamService(server.URL, logger)

	err := service.StartProcessing(context.Background(), uuid.New(), "/path/to/file")
	assert.Error(t, err)
	// MOD-P1-RES-002: Le message d'erreur change avec le retry (après 3 tentatives)
	// Error message is "stream server request failed after 3 attempts: server error: 500"
	assert.True(t,
		strings.Contains(err.Error(), "stream server returned non-200 status after 3 attempts") ||
			strings.Contains(err.Error(), "stream server request failed after 3 attempts"),
		"Error should mention retry failure, got: %s", err.Error())
}
