using NBitcoin.JsonConverters;
using Newtonsoft.Json;
using Newtonsoft.Json.Converters;
using Nostr.Client.Json;
using Nostr.Client.Messages;
using Nostr.Client.Messages.Metadata;
using ProtoBuf;

namespace NostrServices.Client;

[ProtoContract]
public class CompactProfile
{
    [ProtoMember(1)]
    [JsonProperty("pubkey")]
    [JsonConverter(typeof(HexJsonConverter))]
    public byte[] PubKey { get; init; } = null!;

    [ProtoMember(2)]
    [JsonProperty("name")]
    public string? Name { get; init; }

    [ProtoMember(3)]
    [JsonProperty("about")]
    public string? About { get; init; }

    [ProtoMember(4)]
    [JsonProperty("picture")]
    public string? Picture { get; init; }

    [ProtoMember(5)]
    [JsonProperty("nip05")]
    public string? Nip05 { get; init; }

    [ProtoMember(6)]
    [JsonProperty("lud16")]
    public string? Lud16 { get; init; }

    [ProtoMember(7)]
    [JsonProperty("banner")]
    public string? Banner { get; init; }

    [ProtoMember(8)]
    [JsonProperty("created")]
    [JsonConverter(typeof(UnixDateTimeConverter))]
    public DateTime Created { get; init; }

    public static CompactProfile? FromNostrEvent(NostrEvent ev)
    {
        var meta = NostrJson.Deserialize<NostrMetadata>(ev.Content);
        if (meta != default)
        {
            return new()
            {
                PubKey = Convert.FromHexString(ev.Pubkey!),
                Name = meta.Name,
                About = meta.About,
                Picture = meta.Picture,
                Nip05 = meta.Nip05,
                Lud16 = meta.Lud16,
                Banner = meta.Banner,
                Created = ev.CreatedAt!.Value
            };
        }

        return default;
    }
}
