using System.Security.Cryptography;
using JobTrackerApi.Data;
using JobTrackerApi.Models;
using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.Configuration;

namespace JobTrackerApi.Services;

// Shared by AuthController (local/Google/Microsoft sign-in) and TwoFactorController (the
// post-challenge sign-in) so the httpOnly session cookie + readable CSRF cookie are always
// issued the same way, from one place. Also the single place a UserSession row is created, so
// every JWT this app ever hands out has a matching server-side row Program.cs can revoke.
public static class AppSessionIssuer
{
    public static async Task IssueAsync(HttpRequest request, HttpResponse response, ITokenService tokens, JobTrackerContext db, IConfiguration cfg, ApplicationUser user, bool rememberMe, bool secureCookies, CancellationToken cancellationToken)
    {
        var minutes = cfg.GetValue("Auth:JwtExpiresMinutes", 60 * 12);
        if (minutes < 5) minutes = 5;
        if (minutes > 60 * 24 * 30) minutes = 60 * 24 * 30;

        var now = DateTimeOffset.UtcNow;
        var session = new UserSession
        {
            Id = Guid.NewGuid().ToString("N"),
            UserId = user.Id,
            DeviceLabel = TrustedDeviceService.DescribeUserAgent(request.Headers["User-Agent"].ToString()),
            CreatedAtUtc = now,
            LastSeenAtUtc = now,
            ExpiresAtUtc = now.AddMinutes(minutes),
        };
        db.UserSessions.Add(session);
        await db.SaveChangesAsync(cancellationToken);

        var token = await tokens.CreateAccessTokenAsync(user, session.Id, cancellationToken);
        response.Cookies.Append(AuthSessionOptions.SessionCookieName, token, AuthSessionOptions.BuildSessionCookie(rememberMe, secureCookies));

        var csrf = Convert.ToHexString(RandomNumberGenerator.GetBytes(32)).ToLowerInvariant();
        response.Cookies.Append(AuthSessionOptions.CsrfCookieName, csrf, AuthSessionOptions.BuildCsrfCookie(rememberMe, secureCookies));
    }
}
