using System.Diagnostics;
using Npgsql.BackendMessages;
using Npgsql.Internal.TypeHandling;
using Npgsql.PostgresTypes;
using NpgsqlTypes;

namespace Npgsql.Internal.TypeHandlers.InternalTypeHandlers;

partial class PgLsnHandler : NpgsqlSimpleTypeHandler<NpgsqlLogSequenceNumber>
{
    public PgLsnHandler(PostgresType pgType) : base(pgType) {}

    #region Read

    public override NpgsqlLogSequenceNumber Read(NpgsqlReadBuffer buf, int len, FieldDescription? fieldDescription = null)
    {
        Debug.Assert(len == 8);
        return new NpgsqlLogSequenceNumber(buf.ReadUInt64());
    }

    #endregion Read

    #region Write

    public override int ValidateAndGetLength(NpgsqlLogSequenceNumber value, NpgsqlParameter? parameter) => 8;

    public override void Write(NpgsqlLogSequenceNumber value, NpgsqlWriteBuffer buf, NpgsqlParameter? parameter)
        => buf.WriteUInt64((ulong)value);

    #endregion Write
}

partial class PgLsnHandler
{
    public override int ValidateObjectAndGetLength(object value, ref NpgsqlLengthCache? lengthCache, NpgsqlParameter? parameter)
        => value switch
        {

            NpgsqlLogSequenceNumber converted => ((INpgsqlSimpleTypeHandler<NpgsqlLogSequenceNumber>)this).ValidateAndGetLength(converted, parameter),


            _ => throw new InvalidCastException($"Can't write CLR type {value.GetType()} with handler type PgLsnHandler")
        };

    public override Task WriteObjectWithLength(object? value, NpgsqlWriteBuffer buf, NpgsqlLengthCache? lengthCache, NpgsqlParameter? parameter, bool async, CancellationToken cancellationToken = default)
        => value switch
        {

            NpgsqlLogSequenceNumber converted => WriteWithLength(converted, buf, lengthCache, parameter, async, cancellationToken),


            DBNull => WriteWithLength(DBNull.Value, buf, lengthCache, parameter, async, cancellationToken),
            null => WriteWithLength(DBNull.Value, buf, lengthCache, parameter, async, cancellationToken),
            _ => throw new InvalidCastException($"Can't write CLR type {value.GetType()} with handler type PgLsnHandler")
        };
}