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

namespace Application.Features.Api.MyPage.UpdateReceiveSettings;

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

        var now = DateTime.UtcNow;

        if (approve.IsReceiveSMS != request.IsReceiveSMS)
        {
            approve.IsReceiveSMS = request.IsReceiveSMS;
            approve.ReceiveSMSConsentAt = now;
        }

        if (approve.IsReceiveEmail != request.IsReceiveEmail)
        {
            approve.IsReceiveEmail = request.IsReceiveEmail;
            approve.ReceiveEmailConsentAt = now;
        }

        if (approve.IsReceiveNote != request.IsReceiveNote)
        {
            approve.IsReceiveNote = request.IsReceiveNote;
            approve.ReceiveNoteConsentAt = now;
        }

        await db.SaveChangesAsync(ct);

        return Result.Success();
    }
}