package handlers

import (
	"bytes"
	"encoding/json"
	"net/http"
	"net/http/httptest"
	"testing"

	"veza-backend-api/internal/common"
	"veza-backend-api/internal/types"

	"github.com/gin-gonic/gin"
	"github.com/google/uuid"
	"github.com/stretchr/testify/assert"
	"github.com/stretchr/testify/mock"
	"go.uber.org/zap"
)

// MockUserServiceForSettings implements UserService interface for settings testing
type MockUserServiceForSettings struct {
	mock.Mock
}

func (m *MockUserServiceForSettings) GetUserSettings(userID uuid.UUID) (*types.UserSettingsResponse, error) {
	args := m.Called(userID)
	if args.Get(0) == nil {
		return nil, args.Error(1)
	}
	return args.Get(0).(*types.UserSettingsResponse), args.Error(1)
}

func (m *MockUserServiceForSettings) UpdateUserSettings(userID uuid.UUID, req *types.UpdateSettingsRequest) error {
	args := m.Called(userID, req)
	return args.Error(0)
}

func setupTestSettingsRouter(mockService *MockUserServiceForSettings) *gin.Engine {
	gin.SetMode(gin.TestMode)
	router := gin.New()

	logger := zap.NewNop()
	handler := NewSettingsHandlerWithInterface(mockService, logger)

	api := router.Group("/api/v1")
	api.Use(func(c *gin.Context) {
		// Mock auth middleware - set user_id from header if present
		userIDStr := c.GetHeader("X-User-ID")
		if userIDStr != "" {
			uid, err := uuid.Parse(userIDStr)
			if err == nil {
				common.SetUserIDInContext(c, uid)
			}
		}
		c.Next()
	})
	{
		api.GET("/users/settings", handler.GetSettings)
		api.PUT("/users/settings", handler.UpdateSettings)
	}

	return router
}

func TestSettingsHandler_GetSettings_Success(t *testing.T) {
	// Setup
	mockService := new(MockUserServiceForSettings)
	router := setupTestSettingsRouter(mockService)

	userID := uuid.New()
	expectedSettings := &types.UserSettingsResponse{
		Notifications: types.NotificationSettings{
			Email: true,
			Push:  true,
		},
		Privacy: types.PrivacySettings{
			ProfileVisibility: "public",
			PlaylistsPublic:   true,
		},
		Content: types.ContentSettings{
			ExplicitContent: false,
		},
		Preferences: types.PreferenceSettings{
			Language:   "en",
			Timezone:   "UTC",
			DateFormat: "YYYY-MM-DD",
		},
	}

	mockService.On("GetUserSettings", userID).Return(expectedSettings, nil)

	// Execute
	req, _ := http.NewRequest("GET", "/api/v1/users/settings", nil)
	req.Header.Set("X-User-ID", userID.String())
	w := httptest.NewRecorder()
	router.ServeHTTP(w, req)

	// Assert
	assert.Equal(t, http.StatusOK, w.Code)
	mockService.AssertExpectations(t)
}

func TestSettingsHandler_GetSettings_Unauthorized(t *testing.T) {
	// Setup
	mockService := new(MockUserServiceForSettings)
	router := setupTestSettingsRouter(mockService)

	// Execute
	req, _ := http.NewRequest("GET", "/api/v1/users/settings", nil)
	w := httptest.NewRecorder()
	router.ServeHTTP(w, req)

	// Assert
	assert.True(t, w.Code == http.StatusUnauthorized || w.Code == http.StatusForbidden)
	mockService.AssertNotCalled(t, "GetUserSettings")
}

func TestSettingsHandler_GetSettings_ServiceError(t *testing.T) {
	// Setup
	mockService := new(MockUserServiceForSettings)
	router := setupTestSettingsRouter(mockService)

	userID := uuid.New()

	mockService.On("GetUserSettings", userID).Return(nil, assert.AnError)

	// Execute
	req, _ := http.NewRequest("GET", "/api/v1/users/settings", nil)
	req.Header.Set("X-User-ID", userID.String())
	w := httptest.NewRecorder()
	router.ServeHTTP(w, req)

	// Assert
	assert.Equal(t, http.StatusInternalServerError, w.Code)
	mockService.AssertExpectations(t)
}

func TestSettingsHandler_UpdateSettings_Success(t *testing.T) {
	// Setup
	mockService := new(MockUserServiceForSettings)
	router := setupTestSettingsRouter(mockService)

	userID := uuid.New()
	reqBody := types.UpdateSettingsRequest{
		Notifications: &types.NotificationSettings{
			Email: true,
			Push:  false,
		},
		Preferences: &types.PreferenceSettings{
			Language:   "fr",
			Timezone:   "Europe/Paris",
			DateFormat: "DD-MM-YYYY",
		},
	}

	mockService.On("UpdateUserSettings", userID, &reqBody).Return(nil)

	body, _ := json.Marshal(reqBody)

	// Execute
	req, _ := http.NewRequest("PUT", "/api/v1/users/settings", bytes.NewBuffer(body))
	req.Header.Set("Content-Type", "application/json")
	req.Header.Set("X-User-ID", userID.String())
	w := httptest.NewRecorder()
	router.ServeHTTP(w, req)

	// Assert
	assert.Equal(t, http.StatusOK, w.Code)
	mockService.AssertExpectations(t)
}

func TestSettingsHandler_UpdateSettings_Unauthorized(t *testing.T) {
	// Setup
	mockService := new(MockUserServiceForSettings)
	router := setupTestSettingsRouter(mockService)

	reqBody := types.UpdateSettingsRequest{
		Notifications: &types.NotificationSettings{
			Email: true,
		},
	}
	body, _ := json.Marshal(reqBody)

	// Execute
	req, _ := http.NewRequest("PUT", "/api/v1/users/settings", bytes.NewBuffer(body))
	req.Header.Set("Content-Type", "application/json")
	w := httptest.NewRecorder()
	router.ServeHTTP(w, req)

	// Assert
	assert.True(t, w.Code == http.StatusUnauthorized || w.Code == http.StatusForbidden)
	mockService.AssertNotCalled(t, "UpdateUserSettings")
}

func TestSettingsHandler_UpdateSettings_InvalidJSON(t *testing.T) {
	// Setup
	mockService := new(MockUserServiceForSettings)
	router := setupTestSettingsRouter(mockService)

	userID := uuid.New()

	// Execute
	req, _ := http.NewRequest("PUT", "/api/v1/users/settings", bytes.NewBuffer([]byte("invalid json")))
	req.Header.Set("Content-Type", "application/json")
	req.Header.Set("X-User-ID", userID.String())
	w := httptest.NewRecorder()
	router.ServeHTTP(w, req)

	// Assert
	assert.Equal(t, http.StatusBadRequest, w.Code)
	mockService.AssertNotCalled(t, "UpdateUserSettings")
}

func TestSettingsHandler_UpdateSettings_InvalidLanguage(t *testing.T) {
	// Setup
	mockService := new(MockUserServiceForSettings)
	router := setupTestSettingsRouter(mockService)

	userID := uuid.New()
	reqBody := types.UpdateSettingsRequest{
		Preferences: &types.PreferenceSettings{
			Language:   "invalid_lang",
			Timezone:   "UTC",
			DateFormat: "YYYY-MM-DD",
		},
	}

	body, _ := json.Marshal(reqBody)

	// Execute
	req, _ := http.NewRequest("PUT", "/api/v1/users/settings", bytes.NewBuffer(body))
	req.Header.Set("Content-Type", "application/json")
	req.Header.Set("X-User-ID", userID.String())
	w := httptest.NewRecorder()
	router.ServeHTTP(w, req)

	// Assert
	assert.Equal(t, http.StatusBadRequest, w.Code)
	mockService.AssertNotCalled(t, "UpdateUserSettings")
}

func TestSettingsHandler_UpdateSettings_InvalidTimezone(t *testing.T) {
	// Setup
	mockService := new(MockUserServiceForSettings)
	router := setupTestSettingsRouter(mockService)

	userID := uuid.New()
	reqBody := types.UpdateSettingsRequest{
		Preferences: &types.PreferenceSettings{
			Language:   "en",
			Timezone:   "Invalid/Timezone",
			DateFormat: "YYYY-MM-DD",
		},
	}

	body, _ := json.Marshal(reqBody)

	// Execute
	req, _ := http.NewRequest("PUT", "/api/v1/users/settings", bytes.NewBuffer(body))
	req.Header.Set("Content-Type", "application/json")
	req.Header.Set("X-User-ID", userID.String())
	w := httptest.NewRecorder()
	router.ServeHTTP(w, req)

	// Assert
	assert.Equal(t, http.StatusBadRequest, w.Code)
	mockService.AssertNotCalled(t, "UpdateUserSettings")
}

func TestSettingsHandler_UpdateSettings_ValidTimezone(t *testing.T) {
	// Setup
	mockService := new(MockUserServiceForSettings)
	router := setupTestSettingsRouter(mockService)

	userID := uuid.New()
	reqBody := types.UpdateSettingsRequest{
		Preferences: &types.PreferenceSettings{
			Language:   "en",
			Timezone:   "America/New_York",
			DateFormat: "YYYY-MM-DD",
		},
	}

	mockService.On("UpdateUserSettings", userID, &reqBody).Return(nil)

	body, _ := json.Marshal(reqBody)

	// Execute
	req, _ := http.NewRequest("PUT", "/api/v1/users/settings", bytes.NewBuffer(body))
	req.Header.Set("Content-Type", "application/json")
	req.Header.Set("X-User-ID", userID.String())
	w := httptest.NewRecorder()
	router.ServeHTTP(w, req)

	// Assert
	assert.Equal(t, http.StatusOK, w.Code)
	mockService.AssertExpectations(t)
}

func TestSettingsHandler_UpdateSettings_ServiceError(t *testing.T) {
	// Setup
	mockService := new(MockUserServiceForSettings)
	router := setupTestSettingsRouter(mockService)

	userID := uuid.New()
	reqBody := types.UpdateSettingsRequest{
		Notifications: &types.NotificationSettings{
			Email: true,
		},
	}

	mockService.On("UpdateUserSettings", userID, &reqBody).Return(assert.AnError)

	body, _ := json.Marshal(reqBody)

	// Execute
	req, _ := http.NewRequest("PUT", "/api/v1/users/settings", bytes.NewBuffer(body))
	req.Header.Set("Content-Type", "application/json")
	req.Header.Set("X-User-ID", userID.String())
	w := httptest.NewRecorder()
	router.ServeHTTP(w, req)

	// Assert
	assert.Equal(t, http.StatusInternalServerError, w.Code)
	mockService.AssertExpectations(t)
}

func TestSettingsHandler_UpdateSettings_NoPreferences(t *testing.T) {
	// Setup
	mockService := new(MockUserServiceForSettings)
	router := setupTestSettingsRouter(mockService)

	userID := uuid.New()
	reqBody := types.UpdateSettingsRequest{
		Notifications: &types.NotificationSettings{
			Email: true,
		},
		// No Preferences field
	}

	mockService.On("UpdateUserSettings", userID, &reqBody).Return(nil)

	body, _ := json.Marshal(reqBody)

	// Execute
	req, _ := http.NewRequest("PUT", "/api/v1/users/settings", bytes.NewBuffer(body))
	req.Header.Set("Content-Type", "application/json")
	req.Header.Set("X-User-ID", userID.String())
	w := httptest.NewRecorder()
	router.ServeHTTP(w, req)

	// Assert
	assert.Equal(t, http.StatusOK, w.Code)
	mockService.AssertExpectations(t)
}

func TestNewSettingsHandler(t *testing.T) {
	// Setup
	mockService := &MockUserServiceForSettings{}
	logger := zap.NewNop()

	// Execute
	handler := NewSettingsHandlerWithInterface(mockService, logger)

	// Assert
	assert.NotNil(t, handler)
	assert.NotNil(t, handler.userService)
	assert.NotNil(t, handler.commonHandler)
}
