using Microsoft.EntityFrameworkCore;
using ScadaLink.Commons.Interfaces.Services;

namespace ScadaLink.ConfigurationDatabase.Services;

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

    public InstanceLocator(ScadaLinkDbContext context)
    {
        _context = context;
    }

    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;
    }
}
