using Microsoft.EntityFrameworkCore;
using ZB.MOM.WW.ScadaBridge.Commons.Interfaces.Services;

namespace ZB.MOM.WW.ScadaBridge.ConfigurationDatabase.Services;

/// <summary>
/// Resolves instance unique names to site identifiers using the configuration database.
/// </summary>
public class InstanceLocator : IInstanceLocator
{
    private readonly ScadaBridgeDbContext _context;

    /// <summary>Initializes the locator with the EF Core database context.</summary>
    /// <param name="context">The database context used to look up instances and sites.</param>
    public InstanceLocator(ScadaBridgeDbContext context)
    {
        _context = context ?? throw new ArgumentNullException(nameof(context));
    }

    /// <inheritdoc />
    public async Task<string?> GetSiteIdForInstanceAsync(
        string instanceUniqueName,
        CancellationToken cancellationToken = default)
    {
        var instance = await _context.Set<Commons.Entities.Instances.Instance>()
            .FirstOrDefaultAsync(i => i.UniqueName == instanceUniqueName, cancellationToken);

        if (instance == null)
            return null;

        var site = await _context.Set<Commons.Entities.Sites.Site>()
            .FindAsync(new object[] { instance.SiteId }, cancellationToken);

        return site?.SiteIdentifier;
    }
}
