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;
using System;
using Ablera.Serdica.Microservice.Consumer.Contracts;
using static Ablera.Serdica.Authority.Constants.ConstantsClass;

namespace Ablera.Serdica.NotificationService.Endpoints;

public record UserSetEnabledLoginRequest
{
    public required string UserGuid { get; init; }
    public required bool LoginEnabled { get; init; }
}

public record UserSetEnabledLoginResponse
{
    public required bool Updated { get; init; }
}

[Command("users_update_user_login_enabled", timeoutInSeconds: 10, methodName: "POST", allowedRoles: [SerdicaClaims.RoleSuperUser])]
public class UpdateUserLoginEnabledEndpoint(
    SerdicaDbContext dbContext)
        : Microservice.Consumer.Contracts.Asynchronous.IEndpointWithRequest<UserSetEnabledLoginRequest, UserSetEnabledLoginResponse>
{
    public async Task<UserSetEnabledLoginResponse> ConsumeAsync(UserSetEnabledLoginRequest request)
    {
        var updated = await dbContext.UserAccounts
            .Where(x => x.UserGuid == request.UserGuid)
            .ExecuteUpdateAsync(x => x.SetProperty(y => y.LockAccount, request.LoginEnabled ? NoKey : YesKey));

        return new UserSetEnabledLoginResponse { Updated = updated > 0 };
    }
}
