package log

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

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

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

func (l *GetErrorLogMessageDetailLogic) GetErrorLogMessageDetail(idStr string) (resp *types.GetErrorLogMessageDetailResponse, err error) {
    if idStr == "" { return &types.GetErrorLogMessageDetailResponse{}, nil }
    id, _ := strconv.ParseInt(idStr, 10, 64)
    row, err := l.svcCtx.LogMessageModel.FindOne(l.ctx, id)
    if err != nil { return nil, err }
    var uid int64
    if row.UserId != nil { uid = *row.UserId }
    var occurred int64
    if row.OccurredAt != nil { occurred = row.OccurredAt.UnixMilli() }
    return &types.GetErrorLogMessageDetailResponse{
        Id: row.Id,
        Platform: row.Platform,
        AppVersion: row.AppVersion,
        OsName: row.OsName,
        OsVersion: row.OsVersion,
        DeviceId: row.DeviceId,
        UserId: uid,
        SessionId: row.SessionId,
        Level: row.Level,
        ErrorCode: row.ErrorCode,
        Message: row.Message,
        Stack: row.Stack,
        ClientIP: row.ClientIP,
        UserAgent: row.UserAgent,
        Locale: row.Locale,
        OccurredAt: occurred,
        CreatedAt: row.CreatedAt.UnixMilli(),
    }, nil
}
