using System.Text;
using System.Text.Json;
using SharepointToolbox.Web.Core.Models;
namespace SharepointToolbox.Web.Infrastructure.Persistence;
///
/// JSON-file index of produced report files (reports-index.json). The files
/// themselves live under {ExportsFolder}/{ProfileId}/; this is the catalogue the
/// per-client "Reports" list and the id-based download endpoint read.
///
public class GeneratedReportRepository
{
private readonly string _filePath;
private readonly SemaphoreSlim _writeLock = new(1, 1);
private static readonly JsonSerializerOptions ReadOpts = new() { PropertyNameCaseInsensitive = true };
private static readonly JsonSerializerOptions WriteOpts = new()
{
WriteIndented = true,
PropertyNamingPolicy = JsonNamingPolicy.CamelCase
};
public GeneratedReportRepository(string filePath) { _filePath = filePath; }
public async Task> LoadAsync()
{
if (!File.Exists(_filePath)) return Array.Empty();
string json;
try { json = await File.ReadAllTextAsync(_filePath, Encoding.UTF8); }
catch (IOException ex) { throw new InvalidDataException($"Failed to read report index: {_filePath}", ex); }
Root? root;
try { root = JsonSerializer.Deserialize(json, ReadOpts); }
catch (JsonException ex) { throw new InvalidDataException($"Invalid JSON in report index: {_filePath}", ex); }
return (IReadOnlyList?)root?.Reports ?? Array.Empty();
}
public async Task GetAsync(string id)
=> (await LoadAsync()).FirstOrDefault(r => r.Id == id);
public async Task> LoadForProfileAsync(string profileId)
{
var all = await LoadAsync();
return all.Where(r => r.ProfileId == profileId)
.OrderByDescending(r => r.GeneratedUtc)
.ToList();
}
public async Task AddAsync(GeneratedReport report)
{
await _writeLock.WaitAsync();
try
{
var list = (await LoadAsync()).ToList();
list.Add(report);
await WriteUnlockedAsync(list);
}
finally { _writeLock.Release(); }
}
public async Task DeleteAsync(string id)
{
await _writeLock.WaitAsync();
try
{
var list = (await LoadAsync()).ToList();
list.RemoveAll(r => r.Id == id);
await WriteUnlockedAsync(list);
}
finally { _writeLock.Release(); }
}
private async Task WriteUnlockedAsync(IReadOnlyList reports)
{
var json = JsonSerializer.Serialize(new Root { Reports = reports.ToList() }, WriteOpts);
var tmpPath = _filePath + ".tmp";
var dir = Path.GetDirectoryName(_filePath);
if (!string.IsNullOrEmpty(dir)) Directory.CreateDirectory(dir);
await File.WriteAllTextAsync(tmpPath, json, Encoding.UTF8);
JsonDocument.Parse(await File.ReadAllTextAsync(tmpPath, Encoding.UTF8)).Dispose();
File.Move(tmpPath, _filePath, overwrite: true);
}
private sealed class Root { public List Reports { get; set; } = new(); }
}