package handler

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

	"github.com/gin-gonic/gin"
)

func init() {
	gin.SetMode(gin.TestMode)
}

func TestSSOHandlerAuthorize_InvalidContextTypes_ReturnsUnauthorized(t *testing.T) {
	h := &SSOHandler{}
	engine := gin.New()
	engine.GET("/authorize", func(c *gin.Context) {
		c.Set("user_id", "not-int64")
		c.Set("username", 123)
		h.Authorize(c)
	})

	req := httptest.NewRequest(http.MethodGet, "/authorize?client_id=test-client&redirect_uri=https://example.com/callback&response_type=code", nil)
	w := httptest.NewRecorder()
	engine.ServeHTTP(w, req)

	if w.Code != http.StatusUnauthorized {
		t.Fatalf("expected 401, got %d", w.Code)
	}
}

func TestSSOHandlerUserInfo_InvalidContextTypes_ReturnsUnauthorized(t *testing.T) {
	h := &SSOHandler{}
	engine := gin.New()
	engine.GET("/userinfo", func(c *gin.Context) {
		c.Set("user_id", "not-int64")
		c.Set("username", 123)
		h.UserInfo(c)
	})

	req := httptest.NewRequest(http.MethodGet, "/userinfo", nil)
	w := httptest.NewRecorder()
	engine.ServeHTTP(w, req)

	if w.Code != http.StatusUnauthorized {
		t.Fatalf("expected 401, got %d", w.Code)
	}
}

func TestWebhookHandlerCreateWebhook_InvalidContextType_ReturnsUnauthorized(t *testing.T) {
	h := &WebhookHandler{}
	engine := gin.New()
	engine.POST("/webhooks", func(c *gin.Context) {
		c.Set("user_id", "not-int64")
		h.CreateWebhook(c)
	})

	body, err := json.Marshal(map[string]any{
		"name":   "test",
		"url":    "https://example.com/webhook",
		"events": []string{"user.created"},
	})
	if err != nil {
		t.Fatalf("marshal request: %v", err)
	}

	req := httptest.NewRequest(http.MethodPost, "/webhooks", bytes.NewReader(body))
	req.Header.Set("Content-Type", "application/json")
	w := httptest.NewRecorder()
	engine.ServeHTTP(w, req)

	if w.Code != http.StatusUnauthorized {
		t.Fatalf("expected 401, got %d", w.Code)
	}
}

func TestWebhookHandlerListWebhooks_InvalidContextType_ReturnsUnauthorized(t *testing.T) {
	h := &WebhookHandler{}
	engine := gin.New()
	engine.GET("/webhooks", func(c *gin.Context) {
		c.Set("user_id", "not-int64")
		h.ListWebhooks(c)
	})

	req := httptest.NewRequest(http.MethodGet, "/webhooks?page=1&page_size=20", nil)
	w := httptest.NewRecorder()
	engine.ServeHTTP(w, req)

	if w.Code != http.StatusUnauthorized {
		t.Fatalf("expected 401, got %d", w.Code)
	}
}
