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

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

public sealed class NamespaceService(OtOpcUaConfigDbContext db)
{
    public Task<List<Namespace>> ListAsync(long generationId, CancellationToken ct) =>
        db.Namespaces.AsNoTracking()
            .Where(n => n.GenerationId == generationId)
            .OrderBy(n => n.NamespaceId)
            .ToListAsync(ct);

    public async Task<Namespace> AddAsync(
        long draftId, string clusterId, string namespaceUri, NamespaceKind kind, CancellationToken ct)
    {
        var ns = new Namespace
        {
            GenerationId = draftId,
            NamespaceId = $"ns-{Guid.NewGuid():N}"[..20],
            ClusterId = clusterId,
            NamespaceUri = namespaceUri,
            Kind = kind,
        };
        db.Namespaces.Add(ns);
        await db.SaveChangesAsync(ct);
        return ns;
    }
}
