using Microsoft.EntityFrameworkCore;
using ZB.MOM.WW.OtOpcUa.Configuration;
using ZB.MOM.WW.OtOpcUa.Configuration.Entities;

namespace ZB.MOM.WW.OtOpcUa.Admin.Services;

/// <summary>Draft-generation CRUD for <see cref="VirtualTag"/> rows.</summary>
public sealed class VirtualTagService(OtOpcUaConfigDbContext db)
{
    public Task<List<VirtualTag>> ListAsync(long generationId, CancellationToken ct) =>
        db.VirtualTags.AsNoTracking()
            .Where(v => v.GenerationId == generationId)
            .OrderBy(v => v.EquipmentId).ThenBy(v => v.Name)
            .ToListAsync(ct);

    public async Task<VirtualTag> AddAsync(
        long generationId, string equipmentId, string name, string dataType, string scriptId,
        bool changeTriggered, int? timerIntervalMs, bool historize, CancellationToken ct)
    {
        var v = new VirtualTag
        {
            GenerationId = generationId,
            VirtualTagId = $"vt-{Guid.NewGuid():N}"[..20],
            EquipmentId = equipmentId,
            Name = name,
            DataType = dataType,
            ScriptId = scriptId,
            ChangeTriggered = changeTriggered,
            TimerIntervalMs = timerIntervalMs,
            Historize = historize,
        };
        db.VirtualTags.Add(v);
        await db.SaveChangesAsync(ct);
        return v;
    }

    public async Task DeleteAsync(long generationId, string virtualTagId, CancellationToken ct)
    {
        var v = await db.VirtualTags.FirstOrDefaultAsync(x => x.GenerationId == generationId && x.VirtualTagId == virtualTagId, ct);
        if (v is null) return;
        db.VirtualTags.Remove(v);
        await db.SaveChangesAsync(ct);
    }

    public async Task<VirtualTag> UpdateEnabledAsync(long generationId, string virtualTagId, bool enabled, CancellationToken ct)
    {
        var v = await db.VirtualTags.FirstOrDefaultAsync(x => x.GenerationId == generationId && x.VirtualTagId == virtualTagId, ct)
            ?? throw new InvalidOperationException($"VirtualTag '{virtualTagId}' not found in generation {generationId}");
        v.Enabled = enabled;
        await db.SaveChangesAsync(ct);
        return v;
    }
}
