using Microsoft.AspNetCore.Http;
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Diagnostics;
using Microsoft.Extensions.Logging;
using WorkClub.Domain.Interfaces;

namespace WorkClub.Infrastructure.Data.Interceptors;

public class SaveChangesTenantInterceptor : SaveChangesInterceptor
{
    private readonly IHttpContextAccessor _httpContextAccessor;
    private readonly ILogger<SaveChangesTenantInterceptor> _logger;

    public SaveChangesTenantInterceptor(
        IHttpContextAccessor httpContextAccessor,
        ILogger<SaveChangesTenantInterceptor> logger)
    {
        _httpContextAccessor = httpContextAccessor;
        _logger = logger;
    }

    public override ValueTask<InterceptionResult<int>> SavingChangesAsync(
        DbContextEventData eventData,
        InterceptionResult<int> result,
        CancellationToken cancellationToken = default)
    {
        SetTenantIdForNewEntities(eventData.Context);
        return base.SavingChangesAsync(eventData, result, cancellationToken);
    }

    public override InterceptionResult<int> SavingChanges(
        DbContextEventData eventData,
        InterceptionResult<int> result)
    {
        SetTenantIdForNewEntities(eventData.Context);
        return base.SavingChanges(eventData, result);
    }

    private void SetTenantIdForNewEntities(DbContext? context)
    {
        if (context == null)
            return;

        var tenantId = _httpContextAccessor.HttpContext?.Items["TenantId"] as string;

        if (string.IsNullOrWhiteSpace(tenantId))
        {
            _logger.LogWarning("No tenant context available for SaveChanges");
            return;
        }

        var addedEntries = context.ChangeTracker
            .Entries()
            .Where(e => e.State == EntityState.Added && e.Entity is ITenantEntity)
            .ToList();

        foreach (var entry in addedEntries)
        {
            if (entry.Entity is ITenantEntity tenantEntity)
            {
                if (string.IsNullOrWhiteSpace(tenantEntity.TenantId))
                {
                    tenantEntity.TenantId = tenantId;
                    _logger.LogDebug("Set TenantId for entity {EntityType}: {TenantId}",
                        entry.Entity.GetType().Name, tenantId);
                }
            }
        }
    }
}
