using System.Data;
using Dapper;

namespace QuantEngine.Infrastructure.Data;

/// <summary>
/// Dapper has no built-in type handler for System.DateOnly: writing a DateOnly parameter
/// throws NotSupportedException, and reading a DATE column into a DateOnly property throws
/// InvalidCastException. Register once at startup (SqlMapper.AddTypeHandler) to fix both
/// directions everywhere in the codebase.
/// </summary>
public class DateOnlyTypeHandler : SqlMapper.TypeHandler<DateOnly>
{
    public override void SetValue(IDbDataParameter parameter, DateOnly value)
    {
        parameter.DbType = DbType.Date;
        parameter.Value = value.ToDateTime(TimeOnly.MinValue);
    }

    public override DateOnly Parse(object value)
    {
        return value switch
        {
            DateOnly d => d,
            DateTime dt => DateOnly.FromDateTime(dt),
            _ => DateOnly.Parse(value.ToString()!)
        };
    }
}
