using EonaCat.Json;
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations.Schema;
using System.Text;

namespace EonaCat.Logger.LogClient.Models
{
    public class LogEntry
    {
        public string Id { get; set; } = Guid.NewGuid().ToString();

        public DateTime Timestamp { get; set; }

        public string ApplicationName { get; set; } = default!;
        public string ApplicationVersion { get; set; } = default!;
        public string Environment { get; set; } = default!;
        public string MachineName { get; set; } = default!;
        public int Level { get; set; }
        public string Category { get; set; } = default!;
        public string Message { get; set; } = default!;

        public string? Exception { get; set; }
        public string? StackTrace { get; set; }

        [Column(TypeName = "TEXT")]
        public string? PropertiesJson { get; set; }

        [NotMapped]
        public Dictionary<string, object>? Properties
        {
            get => string.IsNullOrEmpty(PropertiesJson)
                ? null
                : JsonHelper.ToObject<Dictionary<string, object>>(PropertiesJson);
            set => PropertiesJson = value == null ? null : JsonHelper.ToJson(value);
        }

        public string? UserId { get; set; }
        public string? SessionId { get; set; }
        public string? RequestId { get; set; }
        public string? CorrelationId { get; set; }


        public static LogEntryDto ToDto(LogEntry entry) => new LogEntryDto()
        {
            Id = entry.Id,
            Timestamp = entry.Timestamp,
            ApplicationName = entry.ApplicationName,
            ApplicationVersion = entry.ApplicationVersion,
            Environment = entry.Environment,
            MachineName = entry.MachineName,
            Level = entry.Level,
            Category = entry.Category,
            Message = entry.Message,
            Exception = entry.Exception,
            StackTrace = entry.StackTrace,
            Properties = entry.Properties,
            UserId = entry.UserId,
            SessionId = entry.SessionId,
            RequestId = entry.RequestId,
            CorrelationId = entry.CorrelationId
        };
    }
}
