namespace Fast.Web.Logic;

public class ActualsGridSettingService(MyDbContext context)
{
    private readonly MyDbContext db = context;

    public async Task<ActualizationFilter?> GetGridSettingsAsync(int userId, int productId)
    {
        return await (
            from q in db.ActualizationFilters
            where q.UserId == userId && q.ProductId == productId
            select new ActualizationFilter
            {
                Id = q.Id,
                UserId = q.UserId,
                ProductId = q.ProductId,
                State = q.State
            }
        ).FirstOrDefaultAsync();
    }

    public async Task SaveGridSettingsAsync(int userId, int productId, string stateJson)
    {
        await db.Database.CreateExecutionStrategy().ExecuteAsync(async () =>
        {
            using var dbContextTransaction = await db.Database.BeginTransactionAsync();

            db.ActualizationFilters.RemoveRange(db.ActualizationFilters.Where(x => x.UserId == userId && x.ProductId == productId));

            var newGridFilter = new ActualizationFilter
            {
                UserId = userId,
                ProductId = productId,
                State = stateJson
            };

            db.ActualizationFilters.Add(newGridFilter);

            await db.SaveChangesAsync();
            await dbContextTransaction.CommitAsync();
        });
    }
}
