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

namespace Application.Features.Api.MyPage.DeleteThumb;

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

        if (string.IsNullOrEmpty(member.Thumb))
        {
            return Result.Failure(Error.Problem("MyPage.ThumbEmpty", "사진이 설정되어 있지 않습니다."));
        }

        // 기존 사진 파일 삭제
        fileStorage.DeleteByUrl(member.Thumb);

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

        return Result.Success();
    }
}