using Microsoft.EntityFrameworkCore;
using ZB.MOM.WW.ScadaBridge.Commons.Entities.Instances;
using ZB.MOM.WW.ScadaBridge.Commons.Entities.Sites;
using ZB.MOM.WW.ScadaBridge.Commons.Entities.Templates;
using ZB.MOM.WW.ScadaBridge.Commons.Types.Enums;
using ZB.MOM.WW.ScadaBridge.Commons.Types.Templates;
using ZB.MOM.WW.ScadaBridge.ConfigurationDatabase.Repositories;
namespace ZB.MOM.WW.ScadaBridge.ConfigurationDatabase.Tests.Repositories;
///
/// WP6 task 6.6 (DEP-4, DEP-6, TPL-4): the targeted, untracked repository reads that replace
/// whole-graph or per-row tracked loads, asserted against real SQL on SQLite.
///
public class TargetedLoadRepositoryTests : IDisposable
{
private readonly ScadaBridgeDbContext _context;
private readonly TemplateEngineRepository _templates;
private readonly DeploymentManagerRepository _deployments;
/// Initializes the test class with an in-memory context and the repositories.
public TargetedLoadRepositoryTests()
{
_context = SqliteTestHelper.CreateInMemoryContext();
_templates = new TemplateEngineRepository(_context, new TemplateGraphWatermark());
_deployments = new DeploymentManagerRepository(_context);
}
/// Releases the resources held by this test class.
public void Dispose()
{
_context.Database.CloseConnection();
_context.Dispose();
}
private async Task<(int SiteId, int TemplateId, List InstanceIds)> SeedAsync(int instances)
{
var site = new Site("Site", "S1");
var template = new Template("T");
_context.Sites.Add(site);
_context.Templates.Add(template);
await _context.SaveChangesAsync();
var ids = new List();
for (var i = 0; i < instances; i++)
{
var instance = new Instance($"I{i:0000}") { SiteId = site.Id, TemplateId = template.Id };
instance.AttributeOverrides.Add(new InstanceAttributeOverride("A") { OverrideValue = i.ToString() });
_context.Instances.Add(instance);
}
await _context.SaveChangesAsync();
ids.AddRange(await _context.Instances.Select(i => i.Id).ToListAsync());
_context.ChangeTracker.Clear();
return (site.Id, template.Id, ids);
}
/// DEP-4: the batched loader returns every requested instance with its children, untracked, across chunks.
/// A task that represents the asynchronous operation.
[Fact]
public async Task GetInstancesByIdsUntracked_LoadsChildren_AcrossChunks_WithoutTracking()
{
var (_, _, ids) = await SeedAsync(620);
var loaded = await _templates.GetInstancesByIdsUntrackedAsync(ids.Append(ids[0]).Append(-1).ToList());
Assert.Equal(ids.Count, loaded.Count);
Assert.All(loaded, i => Assert.Single(i.AttributeOverrides));
Assert.Empty(_context.ChangeTracker.Entries());
}
/// TPL-4: the shallow site read carries no child collections and tracks nothing.
/// A task that represents the asynchronous operation.
[Fact]
public async Task GetInstancesBySiteIdShallow_IsUntracked_AndCarriesNoChildren()
{
var (siteId, _, ids) = await SeedAsync(3);
var shallow = await _templates.GetInstancesBySiteIdShallowAsync(siteId);
Assert.Equal(ids.Count, shallow.Count);
Assert.All(shallow, i => Assert.Empty(i.AttributeOverrides));
Assert.Empty(_context.ChangeTracker.Entries());
}
/// TPL-4: the folder-move collision check is a case-insensitive sibling-name query that excludes the moved template.
/// A task that represents the asynchronous operation.
[Fact]
public async Task TemplateNameExistsInFolder_IsCaseInsensitive_AndExcludesSelf()
{
var folder = new TemplateFolder("F");
_context.TemplateFolders.Add(folder);
await _context.SaveChangesAsync();
var inFolder = new Template("Pump") { FolderId = folder.Id };
var atRoot = new Template("Valve");
_context.Templates.AddRange(inFolder, atRoot);
await _context.SaveChangesAsync();
Assert.True(await _templates.TemplateNameExistsInFolderAsync(folder.Id, "PUMP", atRoot.Id));
Assert.False(await _templates.TemplateNameExistsInFolderAsync(folder.Id, "Pump", inFolder.Id));
Assert.False(await _templates.TemplateNameExistsInFolderAsync(null, "Pump", atRoot.Id));
Assert.True(await _templates.TemplateNameExistsInFolderAsync(null, "valve", inFolder.Id));
}
/// DEP-6: the state read sees a state committed after this context loaded (and tracks) the instance.
/// A task that represents the asynchronous operation.
[Fact]
public async Task GetInstanceState_BypassesIdentityResolution()
{
var (_, _, ids) = await SeedAsync(1);
var tracked = await _context.Instances.SingleAsync(i => i.Id == ids[0]);
Assert.Equal(InstanceState.NotDeployed, tracked.State);
await _context.Database.ExecuteSqlRawAsync(
"UPDATE Instances SET State = {0} WHERE Id = {1}", InstanceState.Disabled.ToString(), ids[0]);
Assert.Equal(InstanceState.NotDeployed, (await _context.Instances.SingleAsync(i => i.Id == ids[0])).State);
Assert.Equal(InstanceState.Disabled, await _deployments.GetInstanceStateAsync(ids[0]));
Assert.Null(await _deployments.GetInstanceStateAsync(-1));
}
}