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

namespace Application.Features.Api.MyPage.Withdraw;

internal sealed class Handler(IAppDbContext db) : ICommandHandler<Command, Result>
{
    public async Task<Result> Handle(Command request, CancellationToken ct)
    {
        if (string.IsNullOrWhiteSpace(request.Password))
        {
            return Result.Failure(Error.Problem("MyPage.PasswordRequired", "비밀번호는 필수입니다."));
        }

        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.VerifyPassword(request.Password))
        {
            return Result.Failure(Error.Problem("MyPage.InvalidPassword", "비밀번호가 올바르지 않습니다."));
        }

        // RefreshToken 무효화
        var refreshTokens = await db.RefreshToken.Where(t => t.MemberID == request.MemberID && !t.IsRevoked).ToListAsync(ct);
        foreach (var token in refreshTokens)
        {
            token.Revoke();
        }

        member.Withdraw();

        await db.SaveChangesAsync(ct);

        return Result.Success();
    }
}