package repository

import (
	"hyapp-admin-server/internal/model"
	"strings"
)

func (s *Store) CreateLoginLog(log model.LoginLog) error {
	return s.db.Create(&log).Error
}

func (s *Store) CreateOperationLog(log model.OperationLog) error {
	return s.db.Create(&log).Error
}

func (s *Store) ListLoginLogs(options ListOptions) ([]model.LoginLog, int64, error) {
	page, pageSize := normalizePage(options.Page, options.PageSize)
	query := s.db.Model(&model.LoginLog{})
	if keyword := strings.TrimSpace(options.Keyword); keyword != "" {
		like := "%" + keyword + "%"
		query = query.Where("username LIKE ? OR ip LIKE ? OR message LIKE ?", like, like, like)
	}

	var total int64
	if err := query.Count(&total).Error; err != nil {
		return nil, 0, err
	}

	var logs []model.LoginLog
	err := query.Order("created_at_ms DESC").Offset((page - 1) * pageSize).Limit(pageSize).Find(&logs).Error
	return logs, total, err
}

func (s *Store) ExportLoginLogs(options ListOptions) ([]model.LoginLog, error) {
	query := s.db.Model(&model.LoginLog{})
	if keyword := strings.TrimSpace(options.Keyword); keyword != "" {
		like := "%" + keyword + "%"
		query = query.Where("username LIKE ? OR ip LIKE ? OR message LIKE ?", like, like, like)
	}

	var logs []model.LoginLog
	err := query.Order("created_at_ms DESC").Find(&logs).Error
	return logs, err
}

func (s *Store) ListOperationLogs(options ListOptions) ([]model.OperationLog, int64, error) {
	page, pageSize := normalizePage(options.Page, options.PageSize)
	query := s.db.Model(&model.OperationLog{})
	if keyword := strings.TrimSpace(options.Keyword); keyword != "" {
		like := "%" + keyword + "%"
		query = query.Where("username LIKE ? OR action LIKE ? OR resource LIKE ? OR detail LIKE ?", like, like, like, like)
	}

	var total int64
	if err := query.Count(&total).Error; err != nil {
		return nil, 0, err
	}

	var logs []model.OperationLog
	err := query.Order("created_at_ms DESC").Offset((page - 1) * pageSize).Limit(pageSize).Find(&logs).Error
	return logs, total, err
}

func (s *Store) ExportOperationLogs(options ListOptions) ([]model.OperationLog, error) {
	query := s.db.Model(&model.OperationLog{})
	if keyword := strings.TrimSpace(options.Keyword); keyword != "" {
		like := "%" + keyword + "%"
		query = query.Where("username LIKE ? OR action LIKE ? OR resource LIKE ? OR detail LIKE ?", like, like, like, like)
	}

	var logs []model.OperationLog
	err := query.Order("created_at_ms DESC").Find(&logs).Error
	return logs, err
}
