using Grpc.Core;
using JOBot.Backend.DAL.Context;
using JOBot.Backend.DAL.Models;
using JOBot.Proto;
using Microsoft.EntityFrameworkCore;
using User = JOBot.Backend.DAL.Models.User;
namespace JOBot.Backend.Services.gRPC;
public class UserService(AppDbContext dbContext) : Proto.User.UserBase
{
///
/// Create user
///
///
///
/// Status of operation (fail if user exists)
public override async Task Register(
RegisterRequest request,
ServerCallContext _)
{
if(!await dbContext.Users
.AnyAsync(x => x.UserId == request.UserId))
{
dbContext.Users.Add(new User
{
UserId = request.UserId,
Username = !string.IsNullOrEmpty(request.Username) ? request.Username : null
});
await dbContext.SaveChangesAsync();
return new RegisterResponse
{
Success = true
};
}
return new RegisterResponse
{
Success = false
};
}
///
/// Get user for client
///
///
///
/// User, or throws RPC exception if not found
public override async Task GetUser(
GetUserRequest request,
ServerCallContext _)
{
var user = await dbContext.Users.FirstOrDefaultAsync(x => x.UserId == request.UserId);
ValidateUserFound(user);
return user!.MapToResponse();
}
///
/// Accept EULA for user
///
///
///
/// Status of operation
public override async Task AcceptEula(AcceptEulaRequest request, ServerCallContext _)
{
var user = await dbContext.Users.FirstOrDefaultAsync(x => x.UserId == request.UserId);
if (user == null)
{
return new AcceptEulaResponse
{
Success = false
};
}
user.Eula = request.EulaAccepted;
await dbContext.SaveChangesAsync();
return new AcceptEulaResponse
{
Success = true
};
}
///
/// Throw RPCException if user not found
///
///
///
private void ValidateUserFound(User? user)
{
if (user == null)
throw new RpcException(new Status(StatusCode.NotFound, "User not found"));
}
}