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

namespace Application.Features.Api.MyPage.DeleteName;

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.Name is null)
        {
            return Result.Failure(Error.Problem("MyPage.NameEmpty", "별명이 설정되어 있지 않습니다."));
        }

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

        member.SetName(null);

        await db.SaveChangesAsync(ct);

        return Result.Success();
    }
}