package repositories

import (
	"log"
	"time"

	"github.com/niangaodev/art-code/config"
	"github.com/niangaodev/art-code/models"
)

// CreateOperationLog 创建操作日志
func CreateOperationLog(operationLog *models.OperationLog) error {
	err := config.DB.Create(operationLog).Error
	if err != nil {
		log.Printf("Error creating operation log: %v", err)
		return err
	}
	return nil
}

// GetOperationLogs 获取操作日志列表
func GetOperationLogs(page, pageSize int) ([]models.OperationLog, int64, error) {
	offset := (page - 1) * pageSize

	var logs []models.OperationLog
	var total int64

	// 获取总记录数
	err := config.DB.Model(&models.OperationLog{}).
		Where("deleted_at = ?", 0).
		Count(&total).Error
	if err != nil {
		log.Printf("Error counting operation logs: %v", err)
		return nil, 0, err
	}

	// 获取分页数据
	err = config.DB.Model(&models.OperationLog{}).
		Where("deleted_at = ?", 0).
		Order("created_at DESC").
		Limit(pageSize).
		Offset(offset).
		Find(&logs).Error
	if err != nil {
		log.Printf("Error querying operation logs: %v", err)
		return nil, 0, err
	}

	return logs, total, nil
}

// BuildOperationLogResponse 构建操作日志响应
func BuildOperationLogResponse(log *models.OperationLog) *models.OperationLogResponse {
	return &models.OperationLogResponse{
		ID:        log.ID,
		UserID:    log.UserID,
		Username:  log.Username,
		IP:        log.IP,
		Path:      log.Path,
		Method:    log.Method,
		Params:    log.Params,
		Status:    log.Status,
		Duration:  log.Duration,
		CreatedAt: time.Unix(log.CreatedAt, 0).Format("2006-01-02 15:04:05"),
	}
}

// BuildOperationLogsResponse 构建操作日志列表响应
func BuildOperationLogsResponse(logs []models.OperationLog) []models.OperationLogResponse {
	var responses []models.OperationLogResponse
	for _, log := range logs {
		responses = append(responses, *BuildOperationLogResponse(&log))
	}
	return responses
}
