using Application.Abstractions.Messaging;
using Application.Abstractions.Data;
using Application.Abstractions.Cache;
using Domain.Entities.Page.Banner;
using SharedKernel.Storage;
using Microsoft.EntityFrameworkCore;

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

public sealed class Handler(IAppDbContext db, IFileStorage fileStorage, ICacheService cache) : ICommandHandler<Command>
{
    public async Task Handle(Command request, CancellationToken ct)
    {
        if (!await db.BannerPosition.AnyAsync(x => x.ID == request.PositionID, ct))
        {
            throw new KeyNotFoundException("��� ��ġ�� ã�� �� �����ϴ�.");
        }

        var bannerItem = BannerItem.Create(
            request.PositionID,
            request.Subject,
            null,
            null,
            request.Link,
            request.Order,
            request.IsActive,
            request.StartAt,
            request.EndAt
        );

        await db.BannerItem.AddAsync(bannerItem);
        await db.SaveChangesAsync(ct);

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

        if (request.DesktopImage is not null)
        {
            bannerItem.SetDesktopImage(
                (await fileStorage.SaveFileAsync(request.DesktopImage, uploadPath, allowedFileExtensions, ct))?.Url
            );
        }

        if (request.MobileImage is not null)
        {
            bannerItem.SetMobileImage(
                (await fileStorage.SaveFileAsync(request.MobileImage, uploadPath, allowedFileExtensions, ct))?.Url
            );
        }

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