using Microsoft.EntityFrameworkCore;
using ZB.MOM.WW.OtOpcUa.Configuration;
using ZB.MOM.WW.OtOpcUa.Configuration.Validation;
namespace ZB.MOM.WW.OtOpcUa.AdminUI.Uns;
///
/// The script-delete usage check (lmxopcua#978, review C-2). VirtualTag.ScriptId,
/// ScriptedAlarm.PredicateScriptId and a Calculation tag's TagConfig.scriptId carry no FK, so
/// a delete used to succeed against a script in use; the next deploy then silently dropped the scripted alarm
/// (and deployed the VirtualTag with an empty expression). The deploy gate now refuses such a draft
/// (VirtualTagScriptNotFound / ScriptedAlarmScriptNotFound / CalculationScriptNotFound);
/// this stops the delete that would create it, and says which rows hold the script.
///
///
/// A check-then-delete is not serialised against a concurrent "bind a VirtualTag to this script" — the deploy
/// gate is the backstop for that window. A real FK (Restrict) would close it but needs a migration.
///
public static class ScriptUsage
{
/// How many using rows are named in the refusal before it summarises the rest.
private const int NamedLimit = 5;
///
/// Describes every row that references , or returns when
/// nothing does and the script may be deleted.
///
/// The context the delete will run on.
/// The script about to be deleted.
/// Cancellation token.
/// A refusal naming the users, or when the script is unused.
public static async Task DescribeBlockingUsageAsync(
OtOpcUaConfigDbContext db, string scriptId, CancellationToken ct = default)
{
ArgumentNullException.ThrowIfNull(db);
ArgumentException.ThrowIfNullOrEmpty(scriptId);
var users = new List();
var vtags = await db.VirtualTags.AsNoTracking()
.Where(v => v.ScriptId == scriptId)
.OrderBy(v => v.VirtualTagId)
.Select(v => new { v.VirtualTagId, v.Name, v.EquipmentId })
.ToListAsync(ct);
users.AddRange(vtags.Select(v => $"virtual tag '{v.Name}' ({v.VirtualTagId}) on equipment {v.EquipmentId}"));
var alarms = await db.ScriptedAlarms.AsNoTracking()
.Where(a => a.PredicateScriptId == scriptId)
.OrderBy(a => a.ScriptedAlarmId)
.Select(a => new { a.ScriptedAlarmId, a.Name, a.EquipmentId })
.ToListAsync(ct);
users.AddRange(alarms.Select(a => $"scripted alarm '{a.Name}' ({a.ScriptedAlarmId}) on equipment {a.EquipmentId}"));
// Calculation tags hold the id inside schemaless JSON: narrow in SQL by substring, then confirm with the
// same parser the deploy gate uses, so a script id that merely appears in another key never blocks.
var calcCandidates = await db.Tags.AsNoTracking()
.Where(t => t.TagConfig.Contains(scriptId))
.OrderBy(t => t.TagId)
.Select(t => new { t.TagId, t.Name, t.TagConfig })
.ToListAsync(ct);
users.AddRange(calcCandidates
.Where(t => string.Equals(DraftValidator.ParseScriptId(t.TagConfig), scriptId, StringComparison.Ordinal))
.Select(t => $"calculation tag '{t.Name}' ({t.TagId})"));
if (users.Count == 0) return null;
var named = string.Join("; ", users.Take(NamedLimit));
var more = users.Count > NamedLimit ? $"; and {users.Count - NamedLimit} more" : string.Empty;
return $"This script is still used by {users.Count} item(s): {named}{more}. "
+ "Point them at another script or delete them first — a deployment would reject them otherwise.";
}
}