using Chronos.Core.Archiving;
using Chronos.Data.Archiving;
using Chronos.Testing;
namespace Chronos.Data.Tests.Archiving;
/// Every archive the service creates, adopts or opens holds its whole layout (BRIEF ยง7, owner request 2026-11-06).
[Category("archive")]
public sealed class ArchiveStructureServiceTests(TestContext context)
{
[Test]
public async Task ANewArchiveGetsItsWholeLayout()
{
await using var db = await ChronosDatabase.OpenAsync(DatabaseOptions.Sqlite(Path.Combine(context.CreateTempDirectory("db"), "chronos.db")), context.Cancellation);
var service = new ArchiveService(db);
var root = Path.Combine(context.CreateTempDirectory("new"), "Chronos", "Archive");
var archive = await service.AdoptAsync(root, "Fresh", context.Cancellation);
var paths = new ArchivePaths(archive.RootPath);
Assert.FileExists(paths.ManifestPath);
Assert.Empty(ArchiveStructure.Missing(paths));
Assert.True(Directory.Exists(paths.TrashPhotosDirectory) && Directory.Exists(paths.TrashVideosDirectory));
}
[Test]
public async Task OpeningAnArchiveMakesTheFoldersItLacksAndTouchesNothingElse()
{
await using var fx = await ArchiveFixture.CreateAsync(context);
var paths = fx.Paths;
var kept = Path.Combine(paths.StagingDirectory, "copy.tmp");
File.WriteAllText(kept, "staged");
var manifest = File.ReadAllBytes(paths.ManifestPath);
// An archive an older Chronos or a copy left without its trash, journal and locks.
Directory.Delete(paths.TrashDirectory, recursive: true);
Directory.Delete(paths.JournalDirectory);
Directory.Delete(paths.LocksDirectory, recursive: true);
await fx.Service.OpenAsync(paths.Root, fx.Ct);
Assert.Empty(ArchiveStructure.Missing(paths));
Assert.Equal("staged", File.ReadAllText(kept));
Assert.BytesEqual(manifest, File.ReadAllBytes(paths.ManifestPath));
}
[Test]
public async Task AnArchiveThatCannotBeLaidOutIsNotCreated()
{
await using var db = await ChronosDatabase.OpenAsync(DatabaseOptions.Sqlite(Path.Combine(context.CreateTempDirectory("db"), "chronos.db")), context.Cancellation);
var service = new ArchiveService(db);
var root = context.CreateTempDirectory("blocked");
// A file where the archive's metadata folder belongs: it stays, and the archive is refused with the reason.
var meta = new ArchivePaths(root).MetaDirectory;
File.WriteAllText(meta, "not a folder");
var error = await Assert.ThrowsAsync(() => service.CreateAsync(root, "Blocked", cancellationToken: context.Cancellation));
Assert.Equal(ArchiveStructureProblem.Failed, error.Report.Problem);
Assert.Equal(meta, error.Report.Folder);
Assert.Equal(error.Report.Message, error.Message);
Assert.Equal("not a folder", File.ReadAllText(meta));
Assert.Empty(await db.Archives.ListAsync(context.Cancellation));
}
}