using EventBus.Abstractions;
using EvitalApp.Appointment.Domain.Context;
using Institution.Integration;
using Institution.Integration.IntegrationEvents;
using MediatR;
using Microsoft.EntityFrameworkCore;
using Serilog;
using Calendar.Abstraction.Dto.Request;
using Calendar.Abstraction.RemoteAbstraction;

namespace EvitalApp.Appointment.Processor.EventHandlers;

public class SlotsSyncedEventHandler : IIntegrationEventHandler<IntegrationEvIntSlotsSynced>
{
    private readonly AppointmentContext _context;
    private readonly IMediator _mediator;
    private readonly IFetchSlotsFromRemove _remoteSlotService;

    public SlotsSyncedEventHandler(
        AppointmentContext context,
        IMediator mediator,
        IFetchSlotsFromRemove remoteSlotService)
    {
        _context = context;
        _mediator = mediator;
        _remoteSlotService = remoteSlotService;
    }

    public async Task Handle(IntegrationEvIntSlotsSynced @event)
    {
        try
        {
            var validServiceCodes = @event.ServiceCodes.Where(x => !string.IsNullOrEmpty(x)).ToList();
            

            var filteredHcps = await _context.Hcps
                .Include(x => x.Institution)
                .Where(x => x.HcpIntegrationSettingsData != null && 
                            x.IsIntegratedHcp &&
                            validServiceCodes.Any(code => 
                                x.HcpIntegrationSettingsData.Contains($"\"IntegrationServiceCode\":\"{code}\"")))
                .ToListAsync();

            if (!filteredHcps.Any())
            {
                Log.Warning("No integrated HCPs found for service codes: {@ServiceCodes}", validServiceCodes);
                return;
            }

            foreach (var hcp in filteredHcps)
            {
                try
                {
                    await _remoteSlotService.FetchAvailableDates(hcp, DateTime.UtcNow, DateTime.UtcNow.AddMonths(6));
                    Log.Information("Successfully processed slot sync for HCP: {@HcpId}", hcp.Id);
                }
                catch (Exception ex)
                {
                    Log.Error(ex, "Error processing slot sync for HCP: {@HcpId} - Error: {@Error}", hcp.Id, ex.Message);
                }
            }
        }
        catch (Exception ex)
        {
            Log.Error(ex, "Error processing slot sync event: {@Event}", @event);
            throw;
        }
    }
}

System.InvalidOperationException: The LINQ expression '__validServiceCodes_0
    .Any(e => StructuralTypeShaperExpression: 
        EvitalApp.Hcps.Domain.Entity.Hcp
        ValueBufferExpression: 
            ProjectionBindingExpression: EmptyProjectionMember
        IsNullable: False
    .HcpIntegrationSettingsData.Contains(string.Format(
        format: ""IntegrationServiceCode":"{0}"", 
        arg0: e)))' could not be translated. Additional information: Translation of method 'string.Format' failed. If this method can be mapped to your custom function, see https://go.microsoft.com/fwlink/?linkid=2132413 for more information.
Translation of method 'string.Format' failed. If this method can be mapped to your custom function, see https://go.microsoft.com/fwlink/?linkid=2132413 for more information. Either rewrite the query in a form that can be translated, or switch to client evaluation explicitly by inserting a call to 'AsEnumerable', 'AsAsyncEnumerable', 'ToList', or 'ToListAsync'. See https://go.microsoft.com/fwlink/?linkid=2101038 for more information.
   at Microsoft.EntityFrameworkCore.Query.QueryableMethodTranslatingExpressionVisitor.Translate(Expression expression)
   at Microsoft.EntityFrameworkCore.Query.RelationalQueryableMethodTranslatingExpressionVisitor.Translate(Expression expression)
   at Microsoft.EntityFrameworkCore.Query.QueryableMethodTranslatingExpressionVisitor.TranslateSubquery(Expression expression)
   at Microsoft.EntityFrameworkCore.Query.RelationalSqlTranslatingExpressionVisitor.VisitMethodCall(MethodCallExpression methodCallExpression)
   at Npgsql.EntityFrameworkCore.PostgreSQL.Query.Internal.NpgsqlSqlTranslatingExpressionVisitor.VisitMethodCall(MethodCallExpression methodCallExpression)
   at Microsoft.EntityFrameworkCore.Query.RelationalSqlTranslatingExpressionVisitor.VisitBinary(BinaryExpression binaryExpression)
   at Npgsql.EntityFrameworkCore.PostgreSQL.Query.Internal.NpgsqlSqlTranslatingExpressionVisitor.VisitBinary(BinaryExpression binaryExpression)
   at Microsoft.EntityFrameworkCore.Query.RelationalSqlTranslatingExpressionVisitor.TranslateInternal(Expression expression, Boolean applyDefaultTypeMapping)
   at Microsoft.EntityFrameworkCore.Query.RelationalSqlTranslatingExpressionVisitor.Translate(Expression expression, Boolean applyDefaultTypeMapping)
   at Microsoft.EntityFrameworkCore.Query.RelationalQueryableMethodTranslatingExpressionVisitor.TranslateExpression(Expression expression, Boolean applyDefaultTypeMapping)
   at Microsoft.EntityFrameworkCore.Query.RelationalQueryableMethodTranslatingExpressionVisitor.TranslateLambdaExpression(ShapedQueryExpression shapedQueryExpression, LambdaExpression lambdaExpression)
   at Microsoft.EntityFrameworkCore.Query.RelationalQueryableMethodTranslatingExpressionVisitor.TranslateWhere(ShapedQueryExpression source, LambdaExpression predicate)
   at Microsoft.EntityFrameworkCore.Query.QueryableMethodTranslatingExpressionVisitor.VisitMethodCall(MethodCallExpression methodCallExpression)
   at Microsoft.EntityFrameworkCore.Query.RelationalQueryableMethodTranslatingExpressionVisitor.VisitMethodCall(MethodCallExpression methodCallExpression)
   at Microsoft.EntityFrameworkCore.Query.QueryableMethodTranslatingExpressionVisitor.VisitMethodCall(MethodCallExpression methodCallExpression)
   at Microsoft.EntityFrameworkCore.Query.RelationalQueryableMethodTranslatingExpressionVisitor.VisitMethodCall(MethodCallExpression methodCallExpression)
   at Microsoft.EntityFrameworkCore.Query.QueryableMethodTranslatingExpressionVisitor.VisitMethodCall(MethodCallExpression methodCallExpression)
   at Microsoft.EntityFrameworkCore.Query.RelationalQueryableMethodTranslatingExpressionVisitor.VisitMethodCall(MethodCallExpression methodCallExpression)
   at Microsoft.EntityFrameworkCore.Query.QueryableMethodTranslatingExpressionVisitor.Translate(Expression expression)
   at Microsoft.EntityFrameworkCore.Query.RelationalQueryableMethodTranslatingExpressionVisitor.Translate(Expression expression)
   at Microsoft.EntityFrameworkCore.Query.QueryCompilationContext.CreateQueryExecutor[TResult](Expression query)
   at Microsoft.EntityFrameworkCore.Storage.Database.CompileQuery[TResult](Expression query, Boolean async)
   at Microsoft.EntityFrameworkCore.Query.Internal.QueryCompiler.CompileQueryCore[TResult](IDatabase database, Expression query, IModel model, Boolean async)
   at Microsoft.EntityFrameworkCore.Query.Internal.QueryCompiler.<>c__DisplayClass12_0`1.<ExecuteAsync>b__0()
   at Microsoft.EntityFrameworkCore.Query.Internal.CompiledQueryCache.GetOrAddQuery[TResult](Object cacheKey, Func`1 compiler)
   at Microsoft.EntityFrameworkCore.Query.Internal.QueryCompiler.ExecuteAsync[TResult](Expression query, CancellationToken cancellationToken)
   at Microsoft.EntityFrameworkCore.Query.Internal.EntityQueryProvider.ExecuteAsync[TResult](Expression expression, CancellationToken cancellationToken)
   at Microsoft.EntityFrameworkCore.Query.Internal.EntityQueryable`1.GetAsyncEnumerator(CancellationToken cancellationToken)
   at System.Runtime.CompilerServices.ConfiguredCancelableAsyncEnumerable`1.GetAsyncEnumerator()
   at Microsoft.EntityFrameworkCore.EntityFrameworkQueryableExtensions.ToListAsync[TSource](IQueryable`1 source, CancellationToken cancellationToken)
   at EvitalApp.Appointment.Processor.EventHandlers.SlotsSyncedEventHandler.Handle(IntegrationEvIntSlotsSynced event)

i get this exception when filteredhcp