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

namespace Application.Features.Api.Channel.ResetWidgetToken;

internal sealed class Handler(IAppDbContext db) : ICommandHandler<Command, Result<string>>
{
    public async Task<Result<string>> Handle(Command request, CancellationToken ct)
    {
        var channel = await db.Channel
            .FirstOrDefaultAsync(c => c.ID == request.ChannelID && c.MemberID == request.MemberID, ct);

        if (channel is null)
        {
            return Result.Failure<string>(Error.NotFound("Channel.NotFound", "채널을 찾을 수 없습니다."));
        }

        channel.ResetWidgetToken();
        await db.SaveChangesAsync(ct);

        return channel.WidgetToken;
    }
}