package admin

import (
	"strconv"
	"verification-platform-backend/internal/database"
	"verification-platform-backend/internal/model"
	"verification-platform-backend/pkg/response"

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

func SetupLogRoutes(r *gin.RouterGroup) {
	logs := r.Group("/logs")
	{
		logs.GET("", handleGetLogs)
	}
}

func handleGetLogs(c *gin.Context) {
	userID := c.GetUint("user_id")

	var appIDs []uint
	database.DB.Model(&model.Application{}).Where("user_id = ?", userID).Pluck("id", &appIDs)

	page, _ := strconv.Atoi(c.DefaultQuery("page", "1"))
	pageSize, _ := strconv.Atoi(c.DefaultQuery("page_size", "20"))
	logType := c.Query("type")
	status := c.Query("status")
	applicationID := c.Query("application_id")
	startDate := c.Query("start_date")
	endDate := c.Query("end_date")
	search := c.Query("search")

	var logs []model.Log
	var total int64

	query := database.DB.Model(&model.Log{})

	if len(appIDs) > 0 {
		query = query.Where("application_id IN ? OR user_id = ?", appIDs, userID)
	} else {
		query = query.Where("user_id = ?", userID)
	}

	if logType != "" && logType != "all" {
		query = query.Where("log_type = ?", logType)
	}

	if status != "" && status != "all" {
		query = query.Where("status = ?", status)
	}

	if applicationID != "" && applicationID != "all" {
		query = query.Where("application_id = ?", applicationID)
	}

	if startDate != "" {
		query = query.Where("created_at >= ?", startDate+" 00:00:00")
	}

	if endDate != "" {
		query = query.Where("created_at <= ?", endDate+" 23:59:59")
	}

	if search != "" {
		query = query.Where("action LIKE ? OR details LIKE ? OR resource LIKE ?", "%"+search+"%", "%"+search+"%", "%"+search+"%")
	}

	query.Count(&total)

	offset := (page - 1) * pageSize
	if err := query.Preload("User").Preload("Application").Preload("AppUser").Order("created_at DESC").Offset(offset).Limit(pageSize).Find(&logs).Error; err != nil {
		response.Error(c, 500, "获取日志失败")
		return
	}

	response.Success(c, gin.H{
		"logs":       logs,
		"total":      total,
		"page":       page,
		"page_size":  pageSize,
		"total_page": (total + int64(pageSize) - 1) / int64(pageSize),
	})
}
