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

namespace Application.Features.Api.Auth.Logout;

internal sealed class Handler(IAppDbContext db, ILogger<Handler> logger) : ICommandHandler<Command, Result>
{
    public async Task<Result> Handle(Command request, CancellationToken ct)
    {
        // 개별 로그아웃
        if (!string.IsNullOrWhiteSpace(request.RefreshToken))
        {
            var refreshToken = await db.RefreshToken.FirstOrDefaultAsync(t => t.Token == request.RefreshToken && t.MemberID == request.MemberID, ct);

            if (refreshToken is not null && !refreshToken.IsRevoked)
            {
                refreshToken.Revoke();
            }
        } 
        else
        {
            // 전체 로그아웃
            var activeTokens = await db.RefreshToken.Where(t => t.MemberID == request.MemberID && !t.IsRevoked).ToListAsync(ct);

            foreach (var token in activeTokens)
            {
                token.Revoke();
            }
        }

        await db.SaveChangesAsync(ct);

        logger.LogInformation("로그아웃 완료");

        return Result.Success();
    }
}