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

namespace Femto.Api.Sessions;

internal static class HttpContextSessionExtensions
{
    public static void SetSession(this HttpContext httpContext, Session session, UserInfo user, ILogger logger)
    {
        var cookieSettings = httpContext.RequestServices.GetService<IOptions<CookieSettings>>();
        
        var secure = cookieSettings?.Value.Secure ?? true;
        var sameSite = secure ? SameSiteMode.None : SameSiteMode.Unspecified;
        var domain = cookieSettings?.Value.Domain;
        var expires = session.Expires;

        logger.LogInformation(
            "cookie settings: Secure={Secure}, SameSite={SameSite}, domain={Domain}, Expires={Expires}",
            secure,
            sameSite,
            domain,
            expires
        );

        httpContext.Response.Cookies.Append(
            "session",
            session.SessionId,
            new CookieOptions
            {
                IsEssential = true,
                Domain = domain,
                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
            {
                Domain = domain,
                IsEssential = true,
                Secure = secure,
                SameSite = sameSite,
                Expires = session.Expires,
            }
        );
    }

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