using Microsoft.EntityFrameworkCore;

namespace demos;

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

        await db.PrepareDatabase(
            """
            create view V_FooBar 
            as 
            select object_id as Id, name as Name, cast(1.0 as real) as Float from sys.tables
            """,
            """
            create procedure I_FooBar(@Name nvarchar(100), @Float real)
            as
            begin
                -- insert ...
                select 1 as Id;
            end
            """);

        await db.FooBars.LoadAsync();
        db.FooBars.Add(new MyDbContextBase.FooBar { Id = 1, Name = "Foo", Float = 1.0f });
        await db.SaveChangesAsync();
    }

    class MyContext : MyDbContextBase
    {
        protected override void OnModelCreating(ModelBuilder modelBuilder)
        {
            modelBuilder.Entity<FooBar>(b =>
            {
                b.Property(x => x.Id).ValueGeneratedOnAdd();
                b.ToSqlQuery("select * from V_FooBar");
                b.InsertUsingStoredProcedure("I_FooBar", i =>
                {
                    i.HasResultColumn(x => x.Id);                  
                    i.HasParameter(x => x.Name);
                    i.HasParameter(x => x.Float);
                });
                b.UpdateUsingStoredProcedure("U_FooBar", u =>
                {
                    u.HasOriginalValueParameter(x => x.Id);
                    u.HasParameter(x => x.Name);
                    u.HasParameter(x => x.Float);
                });
                b.DeleteUsingStoredProcedure("D_FooBar", d =>
                {
                    d.HasOriginalValueParameter(x => x.Id);
                });
            });
        }
    }
}
