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

namespace Application.Features.Admin.Crypto.Category.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.CoinCategory.ToListAsync(ct);
            var dbByID = dbRows.ToDictionary(c => c.ID);

            var requestIDs = items.Where(c => c.ID.HasValue && c.ID.Value > 0).Select(c => c.ID!.Value).ToHashSet();

            var deleteTargets = dbRows.Where(x => !requestIDs.Contains(x.ID)).ToList();

            if (deleteTargets.Count > 0)
            {
                var deleteIDs = deleteTargets.Select(c => c.ID).ToList();
                var hasCoins = await db.CoinCategoryMap.AsNoTracking().AnyAsync(c => deleteIDs.Contains(c.CategoryID), ct);

                if (hasCoins)
                {
                    throw new InvalidOperationException("코인이 등록된 카테고리는 삭제할 수 없습니다. 먼저 해당 코인의 카테고리를 변경하세요.");
                }

                db.CoinCategory.RemoveRange(deleteTargets);
            }

            ushort inserted = 0;
            ushort updated = 0;

            foreach (var row in items)
            {
                if (!row.ID.HasValue || row.ID.Value <= 0)
                {
                    if (await db.CoinCategory.AnyAsync(c => c.Code == row.Code, ct))
                    {
                        throw new InvalidOperationException($"`{row.Code}`는 이미 등록되었습니다.");
                    }

                    db.CoinCategory.Add(
                        CoinCategory.Create(row.Code, row.Name, row.Order, row.IsActive)
                    );

                    inserted++;
                    continue;
                }

                if (!dbByID.TryGetValue(row.ID.Value, out var existing))
                {
                    throw new InvalidOperationException($"존재하지 않는 ID: {row.ID.Value}");
                }

                if (existing.Code != row.Code && await db.CoinCategory.AnyAsync(c => c.Code == row.Code, ct))
                {
                    throw new InvalidOperationException($"`{row.Code}`는 이미 등록되었습니다.");
                }

                existing.Update(row.Code, row.Name, row.Order, row.IsActive);
                updated++;
            }

            ushort deleted = (ushort)deleteTargets.Count;

            await db.SaveChangesAsync(ct);

            await cache.RemoveAsync(CacheKeys.CryptoCategoryActive, ct);

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