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

namespace Application.Features.Admin.MemberGrade.Create
{
    public sealed class Handler(IAppDbContext db, IFileStorage fileStorage) : ICommandHandler<Command>
    {
        public async Task Handle(Command request, CancellationToken ct)
        {
            if (await db.MemberGrade.AnyAsync(x => x.KorName == request.KorName, ct))
            {
                throw new InvalidOperationException($"'{request.KorName}'은(는) 이미 등록된 한글 명입니다.");
            }

            if (await db.MemberGrade.AnyAsync(x => x.EngName == request.EngName, ct))
            {
                throw new InvalidOperationException($"'{request.EngName}'은(는) 이미 등록된 영문 명입니다.");
            }

            var memberGrade = Domain.Entities.Members.MemberGrade.Create(
                request.KorName,
                request.EngName,
                request.Order,
                request.IsActive
            );

            await db.MemberGrade.AddAsync(memberGrade, ct);
            await db.SaveChangesAsync(ct);

            FileStoragePath uploadPath = new(UploadTarget.Upload, UploadFolder.MemberGrade, memberGrade.ID);
            string[] allowedFileExtensions = [".jpg", ".jpeg", ".png", ".gif", ".webp"];
            string? imagePath = null;

            if (request.ImageFile is not null)
            {
                imagePath = (await fileStorage.SaveFileAsync(request.ImageFile, uploadPath, allowedFileExtensions, ct))?.Url;
            }

            memberGrade.Update(
                request.KorName,
                request.EngName,
                request.Description,
                request.Order,
                imagePath,
                request.TextColor,
                request.RequiredExp,
                request.RequiredAttendance,
                request.IsActive
            );

            await db.SaveChangesAsync(ct);
        }
    }
}
