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

namespace Application.Features.Admin.Member.List.Approve;

public sealed class CommandHandler(IAppDbContext db) : ICommandHandler<Command>
{
    public async Task Handle(Command request, CancellationToken ct)
    {
        var member = await db.Member.Include(x => x.MemberApprove).FirstOrDefaultAsync(x => x.ID == request.MemberID, ct);

        if (member is null)
        {
            throw new KeyNotFoundException("회원을 찾을 수 없습니다.");
        }

        var approve = member.MemberApprove;
        var now = DateTime.UtcNow;

        // SMS 수신
        if (request.IsReceiveSMS != approve.IsReceiveSMS)
        {
            approve.IsReceiveSMS = request.IsReceiveSMS;
            approve.ReceiveSMSConsentAt = request.IsReceiveSMS ? now : null;
        }

        // 이메일 수신
        if (request.IsReceiveEmail != approve.IsReceiveEmail)
        {
            approve.IsReceiveEmail = request.IsReceiveEmail;
            approve.ReceiveEmailConsentAt = request.IsReceiveEmail ? now : null;
        }

        // 쪽지 수신
        if (request.IsReceiveNote != approve.IsReceiveNote)
        {
            approve.IsReceiveNote = request.IsReceiveNote;
            approve.ReceiveNoteConsentAt = request.IsReceiveNote ? now : null;
        }

        // 투자 현황 공개
        if (request.IsDisclosureInvest != approve.IsDisclosureInvest)
        {
            approve.IsDisclosureInvest = request.IsDisclosureInvest;
            approve.DisclosureInvestConsentAt = request.IsDisclosureInvest ? now : null;
        }

        await db.SaveChangesAsync(ct);
    }
}