using Npgsql.BackendMessages;
using Npgsql.Internal.TypeHandling;
using Npgsql.PostgresTypes;

namespace Npgsql.Internal.TypeHandlers;

/// <summary>
/// A type handler for the PostgreSQL bool data type.
/// </summary>
/// <remarks>
/// See https://www.postgresql.org/docs/current/static/datatype-boolean.html.
///
/// The type handler API allows customizing Npgsql's behavior in powerful ways. However, although it is public, it
/// should be considered somewhat unstable, and may change in breaking ways, including in non-major releases.
/// Use it at your own risk.
/// </remarks>
public partial class BoolHandler : NpgsqlSimpleTypeHandler<bool>
{
    public BoolHandler(PostgresType pgType) : base(pgType) { }

    /// <inheritdoc />
    public override bool Read(NpgsqlReadBuffer buf, int len, FieldDescription? fieldDescription = null)
        => buf.ReadByte() != 0;

    /// <inheritdoc />
    public override int ValidateAndGetLength(bool value, NpgsqlParameter? parameter)
        => 1;

    /// <inheritdoc />
    public override void Write(bool value, NpgsqlWriteBuffer buf, NpgsqlParameter? parameter)
        => buf.WriteByte(value ? (byte)1 : (byte)0);
}

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

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


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

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

            Boolean 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 BoolHandler")
        };
}