using Femto.Common.Domain;
using Femto.Common.Infrastructure.DbConnection;
using Femto.Modules.Auth.Application.Dto;
using Femto.Modules.Auth.Data;
using Microsoft.EntityFrameworkCore;

namespace Femto.Modules.Auth.Application.Interface.RefreshUserSession;

internal class RefreshUserSessionCommandHandler(AuthContext context)
    : ICommandHandler<RefreshUserSessionCommand, RefreshUserSessionResult>
{
    public async Task<RefreshUserSessionResult> Handle(
        RefreshUserSessionCommand request,
        CancellationToken cancellationToken
    )
    {
        if (request.CurrentUser.Id != request.ForUser)
            throw new DomainError("invalid request");

        var user = await context.Users.SingleOrDefaultAsync(
            u => u.Id == request.ForUser,
            cancellationToken
        );

        if (user is null)
            throw new DomainError("invalid request");

        var session = user.PossiblyRefreshSession(request.CurrentUser.SessionId);

        return new(new Session(session), new UserInfo(user));
    }
}
