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

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

public sealed class DriverInstanceService(OtOpcUaConfigDbContext db)
{
    public Task<List<DriverInstance>> ListAsync(long generationId, CancellationToken ct) =>
        db.DriverInstances.AsNoTracking()
            .Where(d => d.GenerationId == generationId)
            .OrderBy(d => d.DriverInstanceId)
            .ToListAsync(ct);

    public async Task<DriverInstance> AddAsync(
        long draftId, string clusterId, string namespaceId, string name, string driverType,
        string driverConfigJson, CancellationToken ct)
    {
        var di = new DriverInstance
        {
            GenerationId = draftId,
            DriverInstanceId = $"drv-{Guid.NewGuid():N}"[..20],
            ClusterId = clusterId,
            NamespaceId = namespaceId,
            Name = name,
            DriverType = driverType,
            DriverConfig = driverConfigJson,
        };
        db.DriverInstances.Add(di);
        await db.SaveChangesAsync(ct);
        return di;
    }
}
