namespace JobsMedical.Web.Services;

/// <summary>
/// Resolves the current anonymous visitor id for the request. The id is created and written to
/// the <c>hk_vid</c> cookie by <see cref="VisitorCookieMiddleware"/>; this scoped accessor just
/// reads it back out of <c>HttpContext.Items</c>.
/// </summary>
public class VisitorContext
{
    public const string CookieName = "hk_vid";
    public const string ItemKey = "VisitorId";

    private readonly IHttpContextAccessor _http;
    public VisitorContext(IHttpContextAccessor http) => _http = http;

    public string VisitorId =>
        _http.HttpContext?.Items[ItemKey] as string ?? "";
}

/// <summary>
/// Ensures every visitor carries a stable <c>hk_vid</c> cookie (a GUID) so we can track interest
/// from the first visit, before any login. On login we link this id to the user account.
/// </summary>
public class VisitorCookieMiddleware
{
    private readonly RequestDelegate _next;
    public VisitorCookieMiddleware(RequestDelegate next) => _next = next;

    public async Task InvokeAsync(HttpContext ctx)
    {
        var id = ctx.Request.Cookies[VisitorContext.CookieName];
        if (string.IsNullOrWhiteSpace(id))
        {
            id = Guid.NewGuid().ToString();
            ctx.Response.Cookies.Append(VisitorContext.CookieName, id, new CookieOptions
            {
                HttpOnly = true,
                IsEssential = true,                  // functional, not tracking-consent gated
                SameSite = SameSiteMode.Lax,
                MaxAge = TimeSpan.FromDays(365),
            });
        }
        ctx.Items[VisitorContext.ItemKey] = id;
        await _next(ctx);
    }
}
