package handler

import (
	"fmt"
	"net/http"
	"strconv"

	"github.com/gin-gonic/gin"

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

// LogHandler handles log requests
type LogHandler struct {
	loginLogService     *service.LoginLogService
	operationLogService *service.OperationLogService
}

// NewLogHandler creates a new LogHandler
func NewLogHandler(loginLogService *service.LoginLogService, operationLogService *service.OperationLogService) *LogHandler {
	return &LogHandler{
		loginLogService:     loginLogService,
		operationLogService: operationLogService,
	}
}

func (h *LogHandler) GetMyLoginLogs(c *gin.Context) {
	userID, ok := getUserIDFromContext(c)
	if !ok {
		c.JSON(http.StatusUnauthorized, gin.H{"error": "unauthorized"})
		return
	}

	page, _ := strconv.Atoi(c.DefaultQuery("page", "1"))
	pageSize, _ := strconv.Atoi(c.DefaultQuery("page_size", "20"))

	logs, total, err := h.loginLogService.GetMyLoginLogs(c.Request.Context(), userID, page, pageSize)
	if err != nil {
		handleError(c, err)
		return
	}

	c.JSON(http.StatusOK, gin.H{
		"list":    logs,
		"total":   total,
		"page":    page,
		"page_size": pageSize,
	})
}

func (h *LogHandler) GetMyOperationLogs(c *gin.Context) {
	userID, ok := getUserIDFromContext(c)
	if !ok {
		c.JSON(http.StatusUnauthorized, gin.H{"error": "unauthorized"})
		return
	}

	page, _ := strconv.Atoi(c.DefaultQuery("page", "1"))
	pageSize, _ := strconv.Atoi(c.DefaultQuery("page_size", "20"))

	logs, total, err := h.operationLogService.GetMyOperationLogs(c.Request.Context(), userID, page, pageSize)
	if err != nil {
		handleError(c, err)
		return
	}

	c.JSON(http.StatusOK, gin.H{
		"list":      logs,
		"total":     total,
		"page":      page,
		"page_size": pageSize,
	})
}

func (h *LogHandler) GetLoginLogs(c *gin.Context) {
	var req service.ListLoginLogRequest
	if err := c.ShouldBindQuery(&req); err != nil {
		c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
		return
	}

	// Use cursor-based pagination when cursor is provided
	if req.Cursor != "" || req.Size > 0 {
		result, err := h.loginLogService.GetLoginLogsCursor(c.Request.Context(), &req)
		if err != nil {
			handleError(c, err)
			return
		}
		c.JSON(http.StatusOK, gin.H{
			"code":    0,
			"message": "success",
			"data":    result,
		})
		return
	}

	// Fallback to legacy offset-based pagination
	logs, total, err := h.loginLogService.GetLoginLogs(c.Request.Context(), &req)
	if err != nil {
		handleError(c, err)
		return
	}

	c.JSON(http.StatusOK, gin.H{
		"list":    logs,
		"total":   total,
		"page":    req.Page,
		"page_size": req.PageSize,
	})
}

func (h *LogHandler) GetOperationLogs(c *gin.Context) {
	var req service.ListOperationLogRequest
	if err := c.ShouldBindQuery(&req); err != nil {
		c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
		return
	}

	// Use cursor-based pagination when cursor is provided
	if req.Cursor != "" || req.Size > 0 {
		result, err := h.operationLogService.GetOperationLogsCursor(c.Request.Context(), &req)
		if err != nil {
			handleError(c, err)
			return
		}
		c.JSON(http.StatusOK, gin.H{
			"code":    0,
			"message": "success",
			"data":    result,
		})
		return
	}

	// Fallback to legacy offset-based pagination
	logs, total, err := h.operationLogService.GetOperationLogs(c.Request.Context(), &req)
	if err != nil {
		handleError(c, err)
		return
	}

	c.JSON(http.StatusOK, gin.H{
		"list":    logs,
		"total":   total,
		"page":    req.Page,
		"page_size": req.PageSize,
	})
}

func (h *LogHandler) ExportLoginLogs(c *gin.Context) {
	var req service.ExportLoginLogRequest
	if err := c.ShouldBindQuery(&req); err != nil {
		c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
		return
	}

	data, filename, contentType, err := h.loginLogService.ExportLoginLogs(c.Request.Context(), &req)
	if err != nil {
		handleError(c, err)
		return
	}

	c.Header("Content-Disposition", fmt.Sprintf("attachment; filename=\"%s\"", filename))
	c.Data(http.StatusOK, contentType, data)
}
