using Application.Auth.DTOs;
using Domain.Ports.Repositories;
using MediatR;

namespace Application.Auth.Commands;

public record LoginCommand(string Username, string Password) : IRequest<AuthResponse>;

public class LoginCommandHandler(
    IUserRepository userRepository,
    IPasswordService passwordService,
    IJwtService jwtService
) : IRequestHandler<LoginCommand, AuthResponse>
{
    public async Task<AuthResponse> Handle(LoginCommand request, CancellationToken ct)
    {
        var user = await userRepository.GetByUsernameAsync(request.Username.ToLowerInvariant(), ct);

        if (user is null)
            return new AuthResponse(false, Error: "Usuario o contrasena incorrectos");

        if (!passwordService.VerifyPassword(request.Password, user.PasswordHash))
            return new AuthResponse(false, Error: "Usuario o contrasena incorrectos");

        user.UpdateLastLogin();
        await userRepository.UpdateAsync(user, ct);

        var token = jwtService.GenerateToken(user);

        return new AuthResponse(
            Success: true,
            Token: token,
            User: new UserInfo(
                user.Id,
                user.Username,
                user.Role,
                user.StudentId,
                user.Student?.Name
            )
        );
    }
}
