package handler

import (
	"net/http"
	"strconv"

	"github.com/gin-gonic/gin"

	apimiddleware "github.com/user-management-system/internal/api/middleware"
	"github.com/user-management-system/internal/service"
)

// WebhookHandler handles webhook requests
type WebhookHandler struct {
	webhookService *service.WebhookService
}

// NewWebhookHandler creates a new WebhookHandler
func NewWebhookHandler(webhookService *service.WebhookService) *WebhookHandler {
	return &WebhookHandler{webhookService: webhookService}
}

// CreateWebhook 创建 Webhook
// @Summary 创建 Webhook
// @Description 创建新的 Webhook 配置
// @Tags Webhook管理
// @Accept json
// @Produce json
// @Security BearerAuth
// @Param request body service.CreateWebhookRequest true "Webhook信息"
// @Success 201 {object} Response{data=domain.Webhook} "Webhook创建成功"
// @Failure 400 {object} Response "请求参数错误"
// @Failure 401 {object} Response "未认证"
// @Failure 500 {object} Response "服务器错误"
// @Router /api/v1/webhooks [post]
func (h *WebhookHandler) CreateWebhook(c *gin.Context) {
	var req service.CreateWebhookRequest
	if err := c.ShouldBindJSON(&req); err != nil {
		c.JSON(http.StatusBadRequest, gin.H{"code": 400, "message": err.Error()})
		return
	}

	creatorID, ok := getUserIDFromContext(c)
	if !ok {
		c.JSON(http.StatusUnauthorized, gin.H{"code": 401, "message": "unauthorized"})
		return
	}

	webhook, err := h.webhookService.CreateWebhook(c.Request.Context(), &req, creatorID)
	if err != nil {
		c.JSON(http.StatusInternalServerError, gin.H{"code": 500, "message": "创建 Webhook 失败"})
		return
	}

	c.JSON(http.StatusCreated, gin.H{"code": 0, "message": "success", "data": webhook})
}

// ListWebhooks 获取 Webhook 列表
// @Summary 获取 Webhook 列表
// @Description 获取当前用户的 Webhook 配置列表
// @Tags Webhook管理
// @Accept json
// @Produce json
// @Security BearerAuth
// @Param page query int false "页码" default(1)
// @Param page_size query int false "每页数量" default(20)
// @Success 200 {object} Response "Webhook列表"
// @Failure 401 {object} Response "未认证"
// @Failure 500 {object} Response "服务器错误"
// @Router /api/v1/webhooks [get]
func (h *WebhookHandler) ListWebhooks(c *gin.Context) {
	page, _ := strconv.Atoi(c.DefaultQuery("page", "1"))
	pageSize, _ := strconv.Atoi(c.DefaultQuery("page_size", "20"))
	if page < 1 {
		page = 1
	}
	if pageSize < 1 || pageSize > 100 {
		pageSize = 20
	}
	offset := (page - 1) * pageSize

	creatorID, ok := getUserIDFromContext(c)
	if !ok {
		c.JSON(http.StatusUnauthorized, gin.H{"code": 401, "message": "unauthorized"})
		return
	}

	webhooks, total, err := h.webhookService.ListWebhooksPaginated(c.Request.Context(), creatorID, offset, pageSize)
	if err != nil {
		c.JSON(http.StatusInternalServerError, gin.H{"code": 500, "message": "获取 Webhook 列表失败"})
		return
	}

	c.JSON(http.StatusOK, gin.H{
		"code":    0,
		"message": "success",
		"data": gin.H{
			"list":      webhooks,
			"total":     total,
			"page":      page,
			"page_size": pageSize,
		},
	})
}

// UpdateWebhook 更新 Webhook
// @Summary 更新 Webhook
// @Description 更新指定 Webhook 的配置
// @Tags Webhook管理
// @Accept json
// @Produce json
// @Security BearerAuth
// @Param id path int true "Webhook ID"
// @Param request body service.UpdateWebhookRequest true "更新信息"
// @Success 200 {object} Response "更新成功"
// @Failure 400 {object} Response "请求参数错误"
// @Failure 401 {object} Response "未认证"
// @Failure 500 {object} Response "服务器错误"
// @Router /api/v1/webhooks/{id} [put]
func (h *WebhookHandler) UpdateWebhook(c *gin.Context) {
	id, err := strconv.ParseInt(c.Param("id"), 10, 64)
	if err != nil {
		c.JSON(http.StatusBadRequest, gin.H{"code": 400, "message": "无效的 Webhook ID"})
		return
	}

	if _, ok := h.authorizeWebhookAccess(c, id); !ok {
		return
	}

	var req service.UpdateWebhookRequest
	if err := c.ShouldBindJSON(&req); err != nil {
		c.JSON(http.StatusBadRequest, gin.H{"code": 400, "message": err.Error()})
		return
	}

	if err := h.webhookService.UpdateWebhook(c.Request.Context(), id, &req); err != nil {
		c.JSON(http.StatusInternalServerError, gin.H{"code": 500, "message": "更新 Webhook 失败"})
		return
	}

	c.JSON(http.StatusOK, gin.H{"code": 0, "message": "更新成功"})
}

// DeleteWebhook 删除 Webhook
// @Summary 删除 Webhook
// @Description 删除指定的 Webhook 配置
// @Tags Webhook管理
// @Produce json
// @Security BearerAuth
// @Param id path int true "Webhook ID"
// @Success 200 {object} Response "删除成功"
// @Failure 400 {object} Response "请求参数错误"
// @Failure 401 {object} Response "未认证"
// @Failure 500 {object} Response "服务器错误"
// @Router /api/v1/webhooks/{id} [delete]
func (h *WebhookHandler) DeleteWebhook(c *gin.Context) {
	id, err := strconv.ParseInt(c.Param("id"), 10, 64)
	if err != nil {
		c.JSON(http.StatusBadRequest, gin.H{"code": 400, "message": "无效的 Webhook ID"})
		return
	}

	if _, ok := h.authorizeWebhookAccess(c, id); !ok {
		return
	}

	if err := h.webhookService.DeleteWebhook(c.Request.Context(), id); err != nil {
		c.JSON(http.StatusInternalServerError, gin.H{"code": 500, "message": "删除 Webhook 失败"})
		return
	}

	c.JSON(http.StatusOK, gin.H{"code": 0, "message": "删除成功"})
}

// GetWebhookDeliveries 获取 Webhook 投递记录
// @Summary 获取 Webhook 投递记录
// @Description 获取指定 Webhook 的最近投递记录
// @Tags Webhook管理
// @Produce json
// @Security BearerAuth
// @Param id path int true "Webhook ID"
// @Param limit query int false "返回记录数量" default(20)
// @Success 200 {object} Response "投递记录列表"
// @Failure 400 {object} Response "请求参数错误"
// @Failure 401 {object} Response "未认证"
// @Failure 500 {object} Response "服务器错误"
// @Router /api/v1/webhooks/{id}/deliveries [get]
func (h *WebhookHandler) GetWebhookDeliveries(c *gin.Context) {
	id, err := strconv.ParseInt(c.Param("id"), 10, 64)
	if err != nil {
		c.JSON(http.StatusBadRequest, gin.H{"code": 400, "message": "无效的 Webhook ID"})
		return
	}

	if _, ok := h.authorizeWebhookAccess(c, id); !ok {
		return
	}

	limit, _ := strconv.Atoi(c.DefaultQuery("limit", "20"))
	if limit < 1 || limit > 100 {
		limit = 20
	}

	deliveries, err := h.webhookService.GetWebhookDeliveries(c.Request.Context(), id, limit)
	if err != nil {
		c.JSON(http.StatusInternalServerError, gin.H{"code": 500, "message": "获取投递记录失败"})
		return
	}

	c.JSON(http.StatusOK, gin.H{"code": 0, "message": "success", "data": gin.H{"deliveries": deliveries}})
}

func (h *WebhookHandler) authorizeWebhookAccess(c *gin.Context, webhookID int64) (int64, bool) {
	userID, ok := getUserIDFromContext(c)
	if !ok {
		c.JSON(http.StatusUnauthorized, gin.H{"code": 401, "message": "unauthorized"})
		return 0, false
	}

	webhook, err := h.webhookService.GetWebhook(c.Request.Context(), webhookID)
	if err != nil {
		handleError(c, err)
		return 0, false
	}

	if webhook.CreatedBy != userID && !apimiddleware.IsAdmin(c) {
		c.JSON(http.StatusForbidden, gin.H{"code": 403, "message": "permission denied"})
		return 0, false
	}

	return userID, true
}
