using System.Text.Json;
using JsonExtensions.Reading;
using PowerKit.Extensions;

namespace DiscordChatExporter.Core.Discord.Data;

// https://discord.com/developers/docs/resources/channel#message-object-message-reference-structure
public record MessageReference(
    MessageReferenceKind Kind,
    Snowflake? MessageId,
    Snowflake? ChannelId,
    Snowflake? GuildId
)
{
    public static MessageReference Parse(JsonElement json)
    {
        var kind =
            json.GetPropertyOrNull("type")?.GetInt32OrNull()?.Pipe(t => (MessageReferenceKind)t)
            ?? MessageReferenceKind.Default;

        var messageId = json.GetPropertyOrNull("message_id")
            ?.GetNonWhiteSpaceStringOrNull()
            ?.Pipe(Snowflake.Parse);

        var channelId = json.GetPropertyOrNull("channel_id")
            ?.GetNonWhiteSpaceStringOrNull()
            ?.Pipe(Snowflake.Parse);

        var guildId = json.GetPropertyOrNull("guild_id")
            ?.GetNonWhiteSpaceStringOrNull()
            ?.Pipe(Snowflake.Parse);

        return new MessageReference(kind, messageId, channelId, guildId);
    }
}
