using System.Text.Json;
using System.Text.Json.Serialization;
using Femto.Api.Auth;
using Femto.Modules.Auth.Application.Dto;

namespace Femto.Api.Sessions;

internal static class HttpContextSessionExtensions
{
    public static void SetSession(
        this HttpContext httpContext,
        Session session,
        UserInfo user,
        CookieSettings cookieSettings
    )
    {
        var secure = cookieSettings.Secure;
        var sameSite = cookieSettings.SameSite ? SameSiteMode.Strict : SameSiteMode.Unspecified;
        var expires = session.Expires;

        httpContext.Response.Cookies.Append(
            "session",
            session.SessionId,
            new CookieOptions
            {
                HttpOnly = true,
                Secure = secure,
                SameSite = sameSite,
                Expires = expires,
            }
        );

        httpContext.Response.Cookies.Append(
            "user",
            JsonSerializer.Serialize(
                user,
                new JsonSerializerOptions
                {
                    PropertyNamingPolicy = JsonNamingPolicy.CamelCase,
                    Converters = { new JsonStringEnumConverter() },
                }
            ),
            new CookieOptions
            {
                Secure = cookieSettings.Secure,
                SameSite = cookieSettings.SameSite ? SameSiteMode.Strict : SameSiteMode.Unspecified,
                Expires = session.Expires,
            }
        );
    }

    public static void DeleteSession(this HttpContext httpContext)
    {
        httpContext.Response.Cookies.Delete("session");
        httpContext.Response.Cookies.Delete("user");
    }
}
