using Application.Abstractions.Messaging;
using Application.Abstractions.Data;
using Application.Abstractions.Cache;
using SharedKernel.Storage;
using Microsoft.EntityFrameworkCore;

namespace Application.Features.Admin.Banner.Item.Update;

public sealed class Handler(IAppDbContext db, IFileStorage fileStorage, ICacheService cache) : ICommandHandler<Command>
{
    public async Task Handle(Command request, CancellationToken ct)
    {
        var bannerItem = await db.BannerItem.FirstOrDefaultAsync(x => x.ID == request.ID, ct);
        if (bannerItem is null)
        {
            throw new KeyNotFoundException("��ʸ� ã�� �� �����ϴ�.");
        }

        if (!await db.BannerPosition.AnyAsync(x => x.ID == request.PositionID, ct))
        {
            throw new KeyNotFoundException("��� ��ġ�� ã�� �� �����ϴ�.");
        }

        FileStoragePath uploadPath = new FileStoragePath(UploadTarget.Upload, UploadFolder.Banner, bannerItem.ID);
        string[] allowedFileExtensions = [".jpg", ".jpeg", ".png", ".gif", ".webp"];
        string? desktopImgPath = bannerItem.DesktopImage;
        string? mobileImgPath = bannerItem.MobileImage;

        if (request.DesktopImage is not null)
        {
            if (!string.IsNullOrEmpty(bannerItem.DesktopImage))
            {
                fileStorage.DeleteByUrl(bannerItem.DesktopImage);
            }

            desktopImgPath = (await fileStorage.SaveFileAsync(request.DesktopImage, uploadPath, allowedFileExtensions, ct))?.Url;
        }

        if (request.MobileImage is not null)
        {
            if (!string.IsNullOrEmpty(bannerItem.MobileImage))
            {
                fileStorage.DeleteByUrl(bannerItem.MobileImage);
            }

            mobileImgPath = (await fileStorage.SaveFileAsync(request.MobileImage, uploadPath, allowedFileExtensions, ct))?.Url;
        }

        bannerItem.Update(
            request.Subject,
            desktopImgPath,
            mobileImgPath,
            request.Link,
            request.Order,
            request.IsActive,
            request.StartAt,
            request.EndAt
        );

        await db.SaveChangesAsync(ct);
        await cache.RemoveByPrefixAsync("banner:", ct);
    }
}