using Application.Abstractions.Data;
using Application.Abstractions.Messaging;
using Domain.Entities.Members.Logs;
using SharedKernel.Results;
using Microsoft.EntityFrameworkCore;

namespace Application.Features.Api.MyPage.DeleteSummary;

internal sealed class Handler(IAppDbContext db) : 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 (member.Summary is null)
        {
            return Result.Failure(Error.Problem("MyPage.SummaryEmpty", "한마디가 설정되어 있지 않습니다."));
        }

        var log = MemberSummaryChangeLog.Create(request.MemberID, member.Summary, null);
        await db.MemberSummaryChangeLog.AddAsync(log, ct);

        member.SetSummary(null);

        await db.SaveChangesAsync(ct);

        return Result.Success();
    }
}