using Indotalent.ConfigBackEnd.Interfaces;
using Indotalent.ConfigFrontEnd.Extensions;
using Microsoft.AspNetCore.Authentication;
using Microsoft.AspNetCore.Identity;

namespace Indotalent.ConfigFrontEnd.Filter;

public class CurrentUserFilter : IEndpointFilter
{
    private readonly ICurrentUserService _currentUserService;

    public CurrentUserFilter(ICurrentUserService currentUserService)
    {
        _currentUserService = currentUserService;
    }

    public async ValueTask<object?> InvokeAsync(EndpointFilterInvocationContext context, EndpointFilterDelegate next)
    {

        var httpContext = context.HttpContext;
        var user = httpContext.User;

        string? userId = user.GetUserId();
        string? email = user.GetEmail();
        string? userName = user.GetUserName();
        string? fullName = user.GetFullName();
        string? tenantId = user.GetTenantId();


        if (string.IsNullOrEmpty(userId))
        {
            userId = httpContext.Request.Headers["X-UserId"].ToString();
            userName = httpContext.Request.Headers["X-UserName"].ToString();
            email = httpContext.Request.Headers["X-Email"].ToString();
            fullName = httpContext.Request.Headers["X-FullName"].ToString();
            tenantId = httpContext.Request.Headers["X-TenantId"].ToString();
        }

        if (!string.IsNullOrEmpty(userId))
        {
            _currentUserService.UserId = userId;
            _currentUserService.UserName = userName;
            _currentUserService.Email = email;
            _currentUserService.FullName = fullName;
            _currentUserService.TenantId = tenantId;
        }

        return await next(context);
    }
}