using Application.Abstractions.Messaging;
using Application.Abstractions.Data;
using Application.Abstractions.Cache;
using Microsoft.EntityFrameworkCore;
using Domain.Entities.Page.Popup;

namespace Application.Features.Admin.Popup.Position.Save;

public sealed class Handler(IAppDbContext db, ICacheService cache) : ICommandHandler<Command, Response>
{
    public async Task<Response> Handle(Command request, CancellationToken ct)
    {
        var items = request.Items ?? [];

        var dbRows = await db.PopupPosition.Include(x => x.Popups).ToListAsync(ct);

        var inserted = 0;
        var updated = 0;
        var deleted = 0;

        var incomingByID = items.Where(x => x.ID.HasValue).ToDictionary(x => x.ID!.Value, x => x);

        foreach (var existing in dbRows)
        {
            if (!incomingByID.TryGetValue(existing.ID, out var row))
            {
                if (existing.Popups.Count > 0)
                {
                    continue;
                }

                db.PopupPosition.Remove(existing);
                deleted++;
                continue;
            }

            if (existing.Code != row.Code || existing.Subject != row.Subject || existing.IsActive != row.IsActive)
            {
                existing.Update(row.Subject, row.IsActive);

                if (existing.Code != row.Code)
                {
                    var prop = typeof(PopupPosition).GetProperty("Code");
                    prop?.SetValue(existing, row.Code);
                }

                updated++;
            }
        }

        var existingIds = dbRows.Select(x => x.ID).ToHashSet();
        foreach (var row in items.Where(x => !x.ID.HasValue))
        {
            if (dbRows.Any(x => x.Code == row.Code))
            {
                continue;
            }

            var entity = PopupPosition.Create(row.Code, row.Subject, row.IsActive);
            db.PopupPosition.Add(entity);
            inserted++;
        }

        if (inserted + updated + deleted > 0)
        {
            await db.SaveChangesAsync(ct);
            await cache.RemoveAsync(CacheKeys.PopupPositionActive, ct);
            await cache.RemoveByPrefixAsync("popup:", ct);
        }

        return new Response(inserted, updated, deleted);
    }
}