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

namespace Application.Features.Api.MyPage.ChangeThumb;

internal sealed class Handler(IAppDbContext db, IFileStorage fileStorage) : ICommandHandler<Command, Result<string?>>
{
    public async Task<Result<string?>> Handle(Command request, CancellationToken ct)
    {
        var member = await db.Member.FirstOrDefaultAsync(m => m.ID == request.MemberID, ct);
        if (member is null)
        {
            return Result.Failure<string?>(Error.NotFound("MyPage.MemberNotFound", "회원 정보를 찾을 수 없습니다."));
        }

        // 기존 사진 삭제
        if (!string.IsNullOrEmpty(member.Thumb))
        {
            fileStorage.DeleteByUrl(member.Thumb);
        }

        string? thumbUrl = null;

        if (request.Thumb is not null && request.Thumb.Length > 0)
        {
            FileStoragePath uploadPath = new(UploadTarget.Upload, UploadFolder.MemberThumb, request.MemberID);
            string[] allowedExtensions = [".jpg", ".jpeg", ".png", ".gif", ".webp"];

            var result = await fileStorage.SaveFileAsync(request.Thumb, uploadPath, allowedExtensions, ct);
            thumbUrl = result?.Url;
        }

        member.SetThumb(thumbUrl);
        await db.SaveChangesAsync(ct);

        return Result.Success<string?>(thumbUrl);
    }
}