using System.Security.Cryptography; using System.Text; using ClassNotify.Server.Data; using ClassNotify.Server.Domain.Entities; using Microsoft.EntityFrameworkCore; namespace ClassNotify.VoucherTool; public static class VoucherGenerator { public static readonly char[] UnambiguousChars = "23456789ABCDEFGHJKMNPQRSTUVWXYZ".ToCharArray(); // 31 unambiguous characters public static string GenerateSingleKey() { var sb = new StringBuilder(19); for (int i = 0; i < 16; i++) { if (i > 0 && i % 4 == 0) sb.Append('-'); var idx = RandomNumberGenerator.GetInt32(UnambiguousChars.Length); // 0 modulo bias sb.Append(UnambiguousChars[idx]); } return sb.ToString(); } public static string ComputeSha256(string input) { var normalized = input.Replace(" ", "").Replace("-", "").Trim().ToUpperInvariant(); var bytes = Encoding.UTF8.GetBytes(normalized); var hash = SHA256.HashData(bytes); return Convert.ToHexString(hash).ToLowerInvariant(); } public static async Task ExecuteBatchExportAsync( ClassNotifyDbContext db, int count, int durationDays, string targetFilePath) { Console.WriteLine($"[VOUCHER GENERATOR] Generating {count} distinct 16-character keys ({durationDays} days)..."); var keys = new HashSet(count); while (keys.Count < count) { keys.Add(GenerateSingleKey()); } var fullTargetPath = Path.GetFullPath(targetFilePath); var targetDir = Path.GetDirectoryName(fullTargetPath) ?? "."; if (!Directory.Exists(targetDir)) Directory.CreateDirectory(targetDir); var tempFilePath = fullTargetPath + $".tmp.{Guid.NewGuid():N}"; var dbCommitted = false; try { // 1. Write secure temp file Console.WriteLine($"[STEP 1] Writing plaintext voucher keys to secure temporary file: {tempFilePath}"); var csvLines = new List { "VoucherCode,DurationDays,GeneratedAtUtc" }; var now = DateTimeOffset.UtcNow; foreach (var key in keys) { csvLines.Add($"{key},{durationDays},{now:O}"); } await File.WriteAllLinesAsync(tempFilePath, csvLines, Encoding.UTF8); // 2. Commit hashes to DB in a transaction Console.WriteLine($"[STEP 2] Inserting {count} SHA-256 CodeHashes into SubscriptionVouchers table..."); await using var tx = await db.Database.BeginTransactionAsync(); foreach (var key in keys) { var hash = ComputeSha256(key); db.SubscriptionVouchers.Add(new SubscriptionVoucher { Id = Guid.NewGuid(), CodeHash = hash, DurationDays = durationDays, IsUsed = false, CreatedAt = now }); } await db.SaveChangesAsync(); await tx.CommitAsync(); dbCommitted = true; Console.WriteLine($"[STEP 2 SUCCESS] Database transaction committed {count} hashes successfully!"); // 3. Atomic rename Console.WriteLine($"[STEP 3] Atomically moving temporary file to final target: {fullTargetPath}"); File.Move(tempFilePath, fullTargetPath, overwrite: true); Console.WriteLine($"[SUCCESS] Batch voucher export complete! Exported: {fullTargetPath}"); } catch (Exception ex) { if (!dbCommitted) { // DB commit failed: temp file has no commercial value and can be safely deleted if (File.Exists(tempFilePath)) { try { File.Delete(tempFilePath); } catch { } } Console.Error.WriteLine($"[ERROR] Database transaction failed. Cleaned up temp file. Reason: {ex.Message}"); } else { // CRITICAL SAFETY INVARIANT: DB has committed! The temp file contains the ONLY plaintext keys in existence. // WE MUST NEVER DELETE IT! Console.ForegroundColor = ConsoleColor.Red; Console.Error.WriteLine("================================================================================"); Console.Error.WriteLine($"[CRITICAL ALERT] Database committed but file move failed: {ex.Message}"); Console.Error.WriteLine($"[CRITICAL ALERT] Plaintext voucher keys are safely preserved at:"); Console.Error.WriteLine($" ==> {tempFilePath}"); Console.Error.WriteLine("[CRITICAL ALERT] DO NOT DELETE THIS TEMPORARY FILE! IT IS THE ONLY RECORD OF KEYS."); Console.Error.WriteLine("================================================================================"); Console.ResetColor(); } throw; } } }