package log

import (
    "context"
    "time"
    logmessage "github.com/perfect-panel/server/internal/model/logmessage"
    "github.com/perfect-panel/server/internal/svc"
    "github.com/perfect-panel/server/internal/types"
    "github.com/perfect-panel/server/pkg/logger"
)

type GetErrorLogMessageListLogic struct {
    logger.Logger
    ctx    context.Context
    svcCtx *svc.ServiceContext
}

func NewGetErrorLogMessageListLogic(ctx context.Context, svcCtx *svc.ServiceContext) *GetErrorLogMessageListLogic {
    return &GetErrorLogMessageListLogic{ Logger: logger.WithContext(ctx), ctx: ctx, svcCtx: svcCtx }
}

func (l *GetErrorLogMessageListLogic) GetErrorLogMessageList(req *types.GetErrorLogMessageListRequest) (resp *types.GetErrorLogMessageListResponse, err error) {
    var start, end time.Time
    if req.Start > 0 { start = time.UnixMilli(req.Start) }
    if req.End > 0 { end = time.UnixMilli(req.End) }
    rows, total, err := l.svcCtx.LogMessageModel.Filter(l.ctx, &logmessage.FilterParams{
        Page: req.Page,
        Size: req.Size,
        Platform: req.Platform,
        Level: req.Level,
        UserID: req.UserId,
        DeviceID: req.DeviceId,
        ErrorCode: req.ErrorCode,
        Keyword: req.Keyword,
        Start: start,
        End: end,
    })
    if err != nil { return nil, err }
    list := make([]types.ErrorLogMessage, 0, len(rows))
    for _, r := range rows {
        var uid int64
        if r.UserId != nil { uid = *r.UserId }
        list = append(list, types.ErrorLogMessage{
            Id: r.Id,
            Platform: r.Platform,
            AppVersion: r.AppVersion,
            OsName: r.OsName,
            OsVersion: r.OsVersion,
            DeviceId: r.DeviceId,
            UserId: uid,
            SessionId: r.SessionId,
            Level: r.Level,
            ErrorCode: r.ErrorCode,
            Message: r.Message,
            CreatedAt: r.CreatedAt.UnixMilli(),
        })
    }
    return &types.GetErrorLogMessageListResponse{ Total: total, List: list }, nil
}
