using System.Security.Cryptography;

namespace ERPCore.Infra.Auth;

/// <summary>
/// Writes/clears the httpOnly session cookies + non-httpOnly CSRF cookie
/// AuthController issues on every session-establishing call (docs/02-SECURITY.md
/// §B.2). SameSite=Strict assumes frontend and ERPCore share a registrable
/// domain (e.g. both on `localhost`, different ports) — a cross-domain
/// deployment would need SameSite=None (+ Secure, which is already set).
/// </summary>
public static class AuthCookieWriter
{
    public static void WriteSession(HttpResponse response, string accessToken, string refreshToken, int expiresInSeconds)
    {
        response.Cookies.Append(JwtAuthExtensions.AccessTokenCookie, accessToken, new CookieOptions
        {
            HttpOnly = true,
            Secure = true,
            SameSite = SameSiteMode.Strict,
            Path = "/",
            MaxAge = TimeSpan.FromSeconds(expiresInSeconds)
        });

        response.Cookies.Append(JwtAuthExtensions.RefreshTokenCookie, refreshToken, new CookieOptions
        {
            HttpOnly = true,
            Secure = true,
            SameSite = SameSiteMode.Strict,
            Path = "/api/v1/auth/refresh-token",
            MaxAge = TimeSpan.FromDays(30)
        });

        response.Cookies.Append(JwtAuthExtensions.CsrfCookie, GenerateCsrfToken(), new CookieOptions
        {
            HttpOnly = false,
            Secure = true,
            SameSite = SameSiteMode.Strict,
            Path = "/",
            MaxAge = TimeSpan.FromSeconds(expiresInSeconds)
        });
    }

    public static void ClearSession(HttpResponse response)
    {
        response.Cookies.Delete(JwtAuthExtensions.AccessTokenCookie, new CookieOptions { Path = "/" });
        response.Cookies.Delete(JwtAuthExtensions.RefreshTokenCookie, new CookieOptions { Path = "/api/v1/auth/refresh-token" });
        response.Cookies.Delete(JwtAuthExtensions.CsrfCookie, new CookieOptions { Path = "/" });
    }

    private static string GenerateCsrfToken() => Convert.ToBase64String(RandomNumberGenerator.GetBytes(32));
}
