using System.Text.Json; using PlotLine.Data; using PlotLine.Models; namespace PlotLine.Services; public interface IProjectRestoreService { Task RestoreAsync(int projectId, int projectRestorePointId); } public sealed class ProjectRestoreService( IProjectRestorePointRepository restorePointRepository, IProjectRestorePointService restorePointService, ILogger logger, IProjectBackupFiles files,Microsoft.AspNetCore.DataProtection.IDataProtectionProvider? protection=null) : IProjectRestoreService { private static readonly JsonSerializerOptions ReadOptions = new() { PropertyNameCaseInsensitive = true, ReadCommentHandling = JsonCommentHandling.Skip, AllowTrailingCommas = true }; private static readonly JsonSerializerOptions RestoreSqlOptions = new() { WriteIndented = false }; public async Task RestoreAsync(int projectId, int projectRestorePointId) { var restorePoint = await restorePointRepository.GetAsync(projectRestorePointId, projectId); if (restorePoint?.JsonData is null) { return Failure("Restore point could not be found."); } ProjectBackupExport? backup; try { backup = JsonSerializer.Deserialize(restorePoint.JsonData, ReadOptions); } catch (JsonException ex) { logger.LogWarning(ex, "Restore point {ProjectRestorePointID} contains invalid JSON.", projectRestorePointId); return Failure("Restore point JSON is invalid. No project data was changed."); } var validationMessage=ProjectBackupCollectionPresence.ValidateRequiredShape(restorePoint.JsonData); if(validationMessage is null) { var missingFields=ProjectBackupStoredFieldContract.Missing(restorePoint.JsonData); if(missingFields.Count>0) { logger.LogWarning("Restore point {RestorePointID} omits stored fields {Fields}; refusing inferred defaults.",projectRestorePointId,string.Join(", ",missingFields)); validationMessage="This older restore point omits stored project fields. Restore was aborted rather than guessing their values. No project data was changed."; } } validationMessage ??= ValidateBackup(projectId,backup); if (validationMessage is not null) { return Failure(validationMessage); } ProjectRestorePoint? safetyBackup; try { safetyBackup=await restorePointService.CreatePreRestoreAsync(projectId,restorePoint.RestorePointName); } catch(Exception ex) { logger.LogError(ex,"Safety backup failed for project {ProjectID}; restore aborted.",projectId); return Failure("A complete safety backup could not be created. Check that referenced uploaded files are available. No project data was changed."); } if (safetyBackup is null) { logger.LogError("PreRestore backup creation failed for project {ProjectID}. Restore was aborted.", projectId); return Failure("A safety backup could not be created. Restore was aborted and no project data was changed."); } try { var completeSafety=await restorePointRepository.GetAsync(safetyBackup.ProjectRestorePointID,projectId); if(completeSafety?.JsonData is null)throw new InvalidDataException("The complete safety backup could not be verified."); if(!ProjectBackupCollectionPresence.HasRecovery(restorePoint.JsonData)){var current=JsonSerializer.Deserialize(completeSafety.JsonData,ReadOptions)!;if(current.Recovery.NativeReviews.Count>0||current.Recovery.IntentAssessments.Count>0||current.Recovery.ExternalReferences.Count>0) return Failure("Older snapshot omits native or Intent author decisions. Replacement refused; safety backup retained.");} var missing=ProjectBackupCollectionPresence.MissingPersistentCollections(restorePoint.JsonData,completeSafety.JsonData,projectId); if(missing.Count>0) { logger.LogWarning("Restore point {RestorePointID} omits existing persistent collections {Collections}; restore aborted.",projectRestorePointId,string.Join(", ",missing)); return new ProjectRestoreResult{Succeeded=false,SafetyBackup=safetyBackup, Message="This older restore point omits existing project information. Restore was aborted to protect it. Your safety backup has been kept."}; } using var fileStage=await files.StageAsync(backup!,importingCopy:false); var restoreJson = ProjectBackupCollectionPresence.PreserveOmissions(restorePoint.JsonData,BookRecoveryRepository.Encode(backup!,protection)); await restorePointRepository.RestoreAsync(projectId, projectRestorePointId, safetyBackup.ProjectRestorePointID, restoreJson); fileStage.Commit(); logger.LogInformation("Project {ProjectID} restored from restore point {ProjectRestorePointID}. Safety backup {SafetyRestorePointID} was created first.", projectId, projectRestorePointId, safetyBackup.ProjectRestorePointID); return new ProjectRestoreResult { Succeeded = true, Message = "Project restored. A safety backup of the previous state was created first.", SafetyBackup = safetyBackup }; } catch (Exception ex) { logger.LogError(ex, "Project restore failed for project {ProjectID} from restore point {ProjectRestorePointID}. Safety backup {SafetyRestorePointID} was retained.", projectId, projectRestorePointId, safetyBackup.ProjectRestorePointID); return new ProjectRestoreResult { Succeeded = false, // These application-defined preflight errors contain fixed, actionable messages. // Unexpected SQL errors still use the generic response below. Message = ex is Microsoft.Data.SqlClient.SqlException { Number: >= 51006 and <= 51024 } refusal ? refusal.Message + " The safety backup was retained." : "Restore failed. The safety backup was created, and the project data was left unchanged.", SafetyBackup = safetyBackup }; } } private static string? ValidateBackup(int projectId, ProjectBackupExport? backup) { if (backup is null) { return "Restore point JSON is invalid. No project data was changed."; } if (!string.Equals(backup.Format, "PlotDirector.ProjectBackup", StringComparison.Ordinal)) { return "Restore point format is not recognised. No project data was changed."; } if (backup.FormatVersion is not ("1.0" or "1.1" or "1.2" or "1.3" or "1.4")) { return "Restore point format version is not supported. No project data was changed."; } if (backup.Project?.ProjectID != projectId) { return "This restore point does not belong to the selected project. No project data was changed."; } var graphError = ProjectBackupMapValidation.Validate(backup) ?? ProjectBackupGraphValidation.Validate(backup) ?? ProjectBackupFiles.Validate(backup); if (graphError is not null) return graphError + " No project data was changed."; return null; } private static ProjectRestoreResult Failure(string message) => new() { Succeeded = false, Message = message }; }