package handlers

import (
	"database/sql"
	"net/http"

	"github.com/gin-gonic/gin"
	"lan-manager/server/db"
	"lan-manager/server/models"
)

type LogHandler struct{}

func NewLogHandler() *LogHandler {
	return &LogHandler{}
}

func (h *LogHandler) List(c *gin.Context) {
	action := c.Query("action")
	date := c.Query("date")
	query := `SELECT id, action, entity_type, entity_id, entity_name, old_value, new_value, source_ip, username, created_at FROM operation_logs WHERE 1=1`
	args := []interface{}{}
	if action != "" {
		query += ` AND action = ?`
		args = append(args, action)
	}
	if date != "" {
		query += ` AND DATE(created_at) = ?`
		args = append(args, date)
	}
	query += ` ORDER BY created_at DESC LIMIT 1000`

	rows, err := db.DB.Query(query, args...)
	if err != nil {
		c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
		return
	}
	defer rows.Close()
	logs := []models.OperationLog{}
	for rows.Next() {
		var l models.OperationLog
		var eid sql.NullInt64
		if err := rows.Scan(&l.ID, &l.Action, &l.EntityType, &eid, &l.EntityName, &l.OldValue, &l.NewValue, &l.SourceIP, &l.Username, &l.CreatedAt); err == nil {
			if eid.Valid {
				l.EntityID = &eid.Int64
			}
			logs = append(logs, l)
		}
	}
	c.JSON(http.StatusOK, logs)
}
