using System.Text;
using System.Text.Json;
using SharepointToolbox.Web.Core.Models;
namespace SharepointToolbox.Web.Infrastructure.Persistence;
///
/// JSON-file store for definitions (schedules.json).
/// Mirrors 's atomic temp-file-then-move write.
/// Mutating helpers (/) perform the
/// read-modify-write under the same lock so concurrent callers don't clobber each other.
///
public class ScheduledReportRepository
{
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 ScheduledReportRepository(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 schedules: {_filePath}", ex); }
Root? root;
try { root = JsonSerializer.Deserialize(json, ReadOpts); }
catch (JsonException ex) { throw new InvalidDataException($"Invalid JSON in schedules: {_filePath}", ex); }
return (IReadOnlyList?)root?.Schedules ?? Array.Empty();
}
public async Task> LoadForProfileAsync(string profileId)
{
var all = await LoadAsync();
return all.Where(s => s.ProfileId == profileId).ToList();
}
public async Task SaveAllAsync(IReadOnlyList schedules)
{
await _writeLock.WaitAsync();
try { await WriteUnlockedAsync(schedules); }
finally { _writeLock.Release(); }
}
public async Task UpsertAsync(ScheduledReport schedule)
{
await _writeLock.WaitAsync();
try
{
var list = (await LoadAsync()).ToList();
var idx = list.FindIndex(s => s.Id == schedule.Id);
if (idx >= 0) list[idx] = schedule; else list.Add(schedule);
await WriteUnlockedAsync(list);
}
finally { _writeLock.Release(); }
}
public async Task DeleteAsync(string id)
{
await _writeLock.WaitAsync();
try
{
var list = (await LoadAsync()).ToList();
list.RemoveAll(s => s.Id == id);
await WriteUnlockedAsync(list);
}
finally { _writeLock.Release(); }
}
private async Task WriteUnlockedAsync(IReadOnlyList schedules)
{
var json = JsonSerializer.Serialize(new Root { Schedules = schedules.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 Schedules { get; set; } = new(); }
}