using System.Data.Common;
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Diagnostics;

namespace EFQueryCustomization;

class CommandInterceptor
{
    public static async Task Demo()
    {
        using var db = new MyContext();

        await db.PrepareDatabase();

        await db.FooBars.Where(x => (x.Id % 2) == 0).Select(x => x.Name).TagWith("foobar").LoadAsync();
    }

    class MyContext : MyDbContextBase
    {
        protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
        {
            base.OnConfiguring(optionsBuilder);
            optionsBuilder.AddInterceptors(new MyCommandInterceptor());
        }
    }

    class MyCommandInterceptor : DbCommandInterceptor
    {
        public override InterceptionResult<DbDataReader> ReaderExecuting(DbCommand command, CommandEventData eventData, InterceptionResult<DbDataReader> result)
        {
            command.CommandText = command.CommandText.Replace("SELECT", "SELECT TOP 10");
            return result;
        }

        public override ValueTask<InterceptionResult<DbDataReader>> ReaderExecutingAsync(DbCommand command, CommandEventData eventData, InterceptionResult<DbDataReader> result, CancellationToken cancellationToken = default)
        {
            command.CommandText = command.CommandText.Replace("SELECT", "SELECT TOP 10");
            return new ValueTask<InterceptionResult<DbDataReader>>(result);
        }
    }
}
