package logmessage

import (
    "context"
    "time"
    "gorm.io/gorm"
)

func NewModel(db *gorm.DB) Model {
    return &customModel{ defaultModel: newDefaultModel(db) }
}

type FilterParams struct {
    Page     int
    Size     int
    Platform string
    Level    uint8
    UserID   int64
    DeviceID string
    ErrorCode string
    Keyword  string
    Start    time.Time
    End      time.Time
}

type customLogMessageModel interface {
    Filter(ctx context.Context, filter *FilterParams) ([]*LogMessage, int64, error)
}

func (m *customModel) Filter(ctx context.Context, filter *FilterParams) ([]*LogMessage, int64, error) {
    tx := m.WithContext(ctx).Model(&LogMessage{}).Order("id DESC")
    if filter == nil {
        filter = &FilterParams{ Page: 1, Size: 10 }
    }
    if filter.Page < 1 { filter.Page = 1 }
    if filter.Size < 1 { filter.Size = 10 }
    if filter.Platform != "" { tx = tx.Where("`platform` = ?", filter.Platform) }
    if filter.Level != 0 { tx = tx.Where("`level` = ?", filter.Level) }
    if filter.UserID != 0 { tx = tx.Where("`user_id` = ?", filter.UserID) }
    if filter.DeviceID != "" { tx = tx.Where("`device_id` = ?", filter.DeviceID) }
    if filter.ErrorCode != "" { tx = tx.Where("`error_code` = ?", filter.ErrorCode) }
    if !filter.Start.IsZero() { tx = tx.Where("`created_at` >= ?", filter.Start) }
    if !filter.End.IsZero() { tx = tx.Where("`created_at` <= ?", filter.End) }
    if filter.Keyword != "" {
        like := "%" + filter.Keyword + "%"
        tx = tx.Where("`message` LIKE ? OR `stack` LIKE ?", like, like)
    }
    var total int64
    var rows []*LogMessage
    err := tx.Count(&total).Limit(filter.Size).Offset((filter.Page-1)*filter.Size).Find(&rows).Error
    return rows, total, err
}
