using System.Diagnostics.CodeAnalysis;
using FastBlog.Core.Models.Users;
using FastBlog.Core.Services;

namespace FastBlog.Web.Middlewares;

public class SimpleAuthMiddleware(SessionService service, RequestDelegate next)
{
    public async Task Invoke(HttpContext context)
    {
        var meta = context.GetEndpoint()?.Metadata.GetMetadata<SimpleAuthAttribute>();
        var sessionToken = context.Request.Cookies["session-t"];
        
        if (sessionToken is null && meta is not null)
        {
            context.Response.Redirect("/");
            return;
        }

        if (sessionToken is null && meta is null)
        {
            await next(context);
            return;
        }
        
        var result = await service.Get(sessionToken!);
        
        if (result.IsError || result.AsOk is null)
        {
            context.Response.Cookies.Delete("session-t");
            context.Response.Redirect("/users/login");
            return;
        }
        
        context.Features.Set(new User
        {
            Id = result.AsOk!.UserId,
            Username = result.AsOk.UserName!,
            Deleted = false
        });
        
        await next(context);
    }
}

internal class SimpleAuthAttribute : Attribute;

public static class SimpleAuthExtensions
{
    public static bool TryGetUser(this HttpContext context, [NotNullWhen(true)] out User? user)
    {
        user = context.Features.Get<User>();
        return user is not null;
    }

    public static bool IsUser(this HttpContext context)
    {
        return context.Features.Get<User>() is not null;
    }
}