package repository

import (
	"gorm.io/gorm"
	"wireguard-dashboard/client"
	"wireguard-dashboard/constant"
	"wireguard-dashboard/http/param"
	"wireguard-dashboard/model/entity"
	"wireguard-dashboard/model/vo"
	"wireguard-dashboard/utils"
)

type systemLog struct {
	*gorm.DB
}

func SystemLog() systemLog {
	return systemLog{
		client.DB,
	}
}

// SaveLog
// @description: 保存记录
// @receiver systemLog
// @param data
// @return err
func (s systemLog) SaveLog(data *entity.SystemLog) (err error) {
	return s.Create(&data).Error
}

// List
// @description: 分页列表
// @receiver s
// @param p
// @return data
// @return total
// @return err
func (s systemLog) List(p param.OnlyPage, loginUser *entity.User) (data []vo.SystemLogItem, total int64, err error) {
	sel := s.Scopes(utils.Page(p.Current, p.Size)).Table("t_system_log as tsl").
		Joins("LEFT JOIN t_user as tu ON tu.id = tsl.user_id").
		Select("tsl.id", "tu.name as username", "tsl.client_ip", "tsl.method", "tsl.status_code", "tsl.host", "tsl.uri", "tsl.created_at").
		Order("tsl.created_at DESC")

	if loginUser.IsAdmin == constant.NormalAdmin {
		sel.Where("tsl.user_id = ?", loginUser.Id)
	}
	err = sel.Find(&data).Offset(-1).Limit(-1).Count(&total).Error
	return
}
