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

namespace Application.Features.Api.MyPage.DeleteIntro;

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.Intro is null)
        {
            return Result.Failure(Error.Problem("MyPage.IntroEmpty", "자기소개가 설정되어 있지 않습니다."));
        }

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

        member.SetIntro(null);

        await db.SaveChangesAsync(ct);

        return Result.Success();
    }
}