using System.Data; using System.Text.Json; using Dapper; using Microsoft.AspNetCore.DataProtection; using PlotLine.Models; namespace PlotLine.Data; public sealed class BookRecoveryRepository(ISqlConnectionFactory factory, IDataProtectionProvider protection) { public async Task Projects(int user) { using var db = factory.CreateConnection(); return (await db.QueryAsync("dbo.BookRecovery", new { Action = "Projects", UserID = user }, commandType: CommandType.StoredProcedure)).ToArray(); } public async Task Origin(int project, int user) { using var db = factory.CreateConnection(); return await db.QuerySingleAsync("dbo.BookRecovery", new { Action = "Origin", ProjectID = project, UserID = user }, commandType: CommandType.StoredProcedure); } public async Task Receipt(Guid operation, int user) { using var db = factory.CreateConnection(); return await db.QuerySingleOrDefaultAsync("dbo.BookRecovery", new { Action = "Receipt", OperationID = operation, UserID = user }, commandType: CommandType.StoredProcedure); } public async Task Begin(Guid operation, int user) { using var db = factory.CreateConnection(); await db.ExecuteAsync("dbo.BookRecovery", new { Action = "Begin", OperationID = operation, UserID = user }, commandType: CommandType.StoredProcedure); } public async Task> Mappings(int project, int user) { using var db = factory.CreateConnection(); return (await db.QueryAsync("dbo.BookRecovery", new { Action = "Mappings", ProjectID = project, UserID = user }, commandType: CommandType.StoredProcedure)).ToArray(); } public async Task RegisterForks(int project,int user,IEnumerable mappings){using var db=factory.CreateConnection();await db.ExecuteAsync("dbo.BookRecovery",new{Action="Forks",ProjectID=project,UserID=user,MappingsJson=JsonSerializer.Serialize(mappings)},commandType:CommandType.StoredProcedure);} public async Task Complete(Guid operation, int project, int user, int books, string hash, IEnumerable mappings) { using var db = factory.CreateConnection(); await db.ExecuteAsync("dbo.BookRecovery", new { Action = "Complete", OperationID = operation, ProjectID = project, UserID = user, BooksCreated = books, RequestHash = hash, MappingsJson = JsonSerializer.Serialize(mappings) }, commandType: CommandType.StoredProcedure); } public static async Task ReadState(ISqlConnectionFactory factory, int project, IDataProtectionProvider? protection, IDbConnection? connection = null, IDbTransaction? transaction = null) { using var owned = connection == null ? factory.CreateConnection() : null; var db = connection ?? owned!; using var rows = await db.QueryMultipleAsync("dbo.ProjectRecovery_State", new { ProjectID = project }, transaction: transaction, commandType: CommandType.StoredProcedure); var result = new ProjectRecoveryState { NativeReviews = (await rows.ReadAsync()).ToList(), IntentAssessments = (await rows.ReadAsync()).ToList() }; var references = await rows.ReadSingleOrDefaultAsync(); result.ExternalReferences = references == null ? [] : JsonSerializer.Deserialize>(references) ?? []; if(!rows.IsConsumed){var paragraphs=(await rows.ReadAsync()).Select(json=>JsonSerializer.Deserialize(json)??throw new InvalidDataException("Invalid paragraph recovery state.")).ToList();if(paragraphs.Count>0)result.ParagraphManuscripts=paragraphs;} foreach(var state in result.ParagraphManuscripts??[])PlotLine.Services.Manuscript.ParagraphRecovery.Detach(state); foreach(var r in result.NativeReviews){ if(r.EncryptedSource!=null){if(protection==null)throw new InvalidOperationException("Source protection is required to export captured reviews safely.");var capture=JsonSerializer.Deserialize(protection.CreateProtector("NativeImport.Source.v1").Unprotect(r.EncryptedSource))??throw new InvalidDataException("Invalid captured source");capture.SessionId=Guid.Empty;r.SourceJson=JsonSerializer.Serialize(capture);r.EncryptedSource=null;} var resultJson=System.Text.Json.Nodes.JsonNode.Parse(r.ResultJson)!.AsObject();resultJson.Remove("CaptureSession");r.ResultJson=resultJson.ToJsonString(); } return result; } public static string ProtectState(ProjectRecoveryState state, IDataProtectionProvider? protection) { // The SQL apply path receives locally protected captures; exported JSON never contains this ciphertext. return JsonSerializer.Serialize(new { Protected = true, state.ExternalReferences, NativeReviews = state.NativeReviews.Select(r => new { r.ReviewID, r.UserID, r.BookID, r.ManuscriptID, r.ChapterStart, r.ChapterEnd, r.ContentHash, r.ResultJson, r.DecisionsJson, r.Version, r.CreatedUtc, EncryptedSource = r.SourceJson == null ? null : (protection ?? throw new InvalidOperationException("Source protection unavailable")).CreateProtector("NativeImport.Source.v1").Protect(r.SourceJson) }), state.IntentAssessments, state.ParagraphManuscripts }); } public static string Encode(ProjectBackupExport backup, IDataProtectionProvider? protection,int[]? appendBooks=null) { var node = System.Text.Json.Nodes.JsonNode.Parse(JsonSerializer.Serialize(backup))!; node["Recovery"] = System.Text.Json.Nodes.JsonNode.Parse(ProtectState(backup.Recovery, protection));if(appendBooks!=null){node["Recovery"]!["AppendOnly"]=true;node["Recovery"]!["AppendBooks"]=JsonSerializer.SerializeToNode(appendBooks);} return node.ToJsonString(); } public async Task ApplyState(int project, ProjectRecoveryState state) { using var db = factory.CreateConnection(); await db.ExecuteAsync("dbo.ProjectRecovery_Apply", new { ProjectID = project, StateJson = ProtectState(state, protection) }, commandType: CommandType.StoredProcedure); } }