package audit

import (
	"fmt"

	"github.com/gin-gonic/gin"
	"hyapp-admin-server/internal/model"
	"hyapp-admin-server/internal/modules/shared"
	"hyapp-admin-server/internal/repository"
	"hyapp-admin-server/internal/response"
)

type Handler struct {
	service *AuditService
}

func New(store *repository.Store) *Handler {
	return &Handler{service: NewService(store)}
}

func (h *Handler) ListLoginLogs(c *gin.Context) {
	options := shared.ListOptions(c)
	logs, total, err := h.service.ListLoginLogs(options)
	if err != nil {
		response.ServerError(c, "获取登录日志失败")
		return
	}
	response.OK(c, response.Page{Items: logs, Page: options.Page, PageSize: options.PageSize, Total: total})
}

func (h *Handler) ListOperationLogs(c *gin.Context) {
	options := shared.ListOptions(c)
	logs, total, err := h.service.ListOperationLogs(options)
	if err != nil {
		response.ServerError(c, "获取操作日志失败")
		return
	}
	response.OK(c, response.Page{Items: logs, Page: options.Page, PageSize: options.PageSize, Total: total})
}

func (h *Handler) ExportLoginLogs(c *gin.Context) {
	export, err := h.service.ExportLoginLogs(shared.ListOptions(c))
	if err != nil {
		response.ServerError(c, "导出登录日志失败")
		return
	}

	shared.OperationLog(c, h, "export-login-logs", "admin_login_logs", "success", fmt.Sprintf("%d logs", export.Count))
	c.Header("Content-Disposition", "attachment; filename="+export.FileName)
	c.Header("Content-Type", "text/csv; charset=utf-8")
	c.Writer.WriteHeader(200)
	_, _ = c.Writer.Write(export.Content)
}

func (h *Handler) ExportOperationLogs(c *gin.Context) {
	export, err := h.service.ExportOperationLogs(shared.ListOptions(c))
	if err != nil {
		response.ServerError(c, "导出操作日志失败")
		return
	}

	shared.OperationLog(c, h, "export-operation-logs", "admin_operation_logs", "success", fmt.Sprintf("%d logs", export.Count))
	c.Header("Content-Disposition", "attachment; filename="+export.FileName)
	c.Header("Content-Type", "text/csv; charset=utf-8")
	c.Writer.WriteHeader(200)
	_, _ = c.Writer.Write(export.Content)
}

func (h *Handler) CreateOperationLog(log model.OperationLog) error {
	return h.service.CreateOperationLog(log)
}

func (h *Handler) LogOperation(event shared.OperationEvent) error {
	return h.service.LogOperation(event)
}
