using Microsoft.Data.Sqlite;

namespace ZB.MOM.WW.MxGateway.Server.Security.Authentication;

/// <summary>Reads API key records from SQLite query results.</summary>
public static class ApiKeyRecordReader
{
    /// <summary>Deserializes a row from the API key table into an ApiKeyRecord.</summary>
    /// <param name="reader">The data reader positioned at the API key row.</param>
    /// <returns>The deserialized API key record.</returns>
    public static ApiKeyRecord Read(SqliteDataReader reader)
    {
        return new ApiKeyRecord(
            KeyId: reader.GetString(0),
            KeyPrefix: reader.GetString(1),
            SecretHash: (byte[])reader["secret_hash"],
            DisplayName: reader.GetString(3),
            Scopes: ApiKeyScopeSerializer.Deserialize(reader.GetString(4)),
            Constraints: ApiKeyConstraintSerializer.Deserialize(reader.IsDBNull(5) ? null : reader.GetString(5)),
            CreatedUtc: DateTimeOffset.Parse(reader.GetString(6), System.Globalization.CultureInfo.InvariantCulture),
            LastUsedUtc: ReadNullableDateTimeOffset(reader, 7),
            RevokedUtc: ReadNullableDateTimeOffset(reader, 8));
    }

    private static DateTimeOffset? ReadNullableDateTimeOffset(SqliteDataReader reader, int ordinal)
    {
        return reader.IsDBNull(ordinal)
            ? null
            : DateTimeOffset.Parse(reader.GetString(ordinal), System.Globalization.CultureInfo.InvariantCulture);
    }
}
