using Ablera.Serdica.Microservice.Consumer.Attributes;
using Ablera.Serdica.Microservice.Consumer.Contracts.Asynchronous;
using Ablera.Serdica.Common.Tools.Exceptions;
using Ablera.Serdica.Authority.Services;
using System.Threading.Tasks;
using Ablera.Serdica.Authentication.Constants;
using Ablera.Serdica.DBModels.Serdica;
using System.Linq;
using Ablera.Serdica.Authority.Models;
using Ablera.Serdica.Extensions.RabbitMQ.Contracts;
using Microsoft.EntityFrameworkCore;

namespace Ablera.Serdica.NotificationService.Endpoints;


[Command("users_get_user_roles", timeoutInSeconds: 10, methodName: "GET", allowedRoles: [SerdicaClaims.IsAuthenticated])]
public class UserRolesEndpoint(
    IEndpointRequestMessageProvider requestMessageProvider,
    SerdicaDbContext dbContext)
        : IEndpointWithNoRequest<string[]>
{
    public async Task<string[]> ConsumeAsync()
    {
        var userAccount = dbContext.UserAccounts.Where(x => x.UserGuid == requestMessageProvider.RequestMessage.UserId)?.FirstOrDefault()
            ?? throw new BaseResultException("account_not_found".AsCode(), "Account associated with the session not found!");

        var userRoles = await dbContext.UserAccounts
            .Where(x => x.UserAccountId == userAccount.UserAccountId)
            .SelectMany(x => x.UserRole1s)
            .Select(x => x.Id)
            .ToArrayAsync();
        if (!userRoles.Any())
        {
            throw new BaseResultException("account_has_no_roles".AsCode(), "Account has not roles set!");
        }
        return userRoles;
    }
}
