using Microsoft.EntityFrameworkCore;
using ZB.MOM.WW.ScadaBridge.Commons.Entities.ExternalSystems;
using ZB.MOM.WW.ScadaBridge.Commons.Interfaces.Repositories;

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

public class ExternalSystemRepository : IExternalSystemRepository
{
    private readonly ScadaBridgeDbContext _context;

    /// <summary>
    /// Initializes a new instance of the ExternalSystemRepository class.
    /// </summary>
    /// <param name="context">The database context for accessing external system data.</param>
    public ExternalSystemRepository(ScadaBridgeDbContext context)
    {
        _context = context ?? throw new ArgumentNullException(nameof(context));
    }

    /// <inheritdoc />
    public async Task<ExternalSystemDefinition?> GetExternalSystemByIdAsync(int id, CancellationToken cancellationToken = default)
        => await _context.Set<ExternalSystemDefinition>().FindAsync(new object[] { id }, cancellationToken);

    /// <inheritdoc />
    // Genuine name-keyed query (server-side WHERE) so the
    // gateway's hot-path resolution does not fetch every system and filter in memory.
    public async Task<ExternalSystemDefinition?> GetExternalSystemByNameAsync(string name, CancellationToken cancellationToken = default)
        => await _context.Set<ExternalSystemDefinition>()
            .FirstOrDefaultAsync(s => s.Name == name, cancellationToken);

    /// <inheritdoc />
    public async Task<IReadOnlyList<ExternalSystemDefinition>> GetAllExternalSystemsAsync(CancellationToken cancellationToken = default)
        => await _context.Set<ExternalSystemDefinition>().ToListAsync(cancellationToken);

    /// <inheritdoc />
    public async Task AddExternalSystemAsync(ExternalSystemDefinition definition, CancellationToken cancellationToken = default)
        => await _context.Set<ExternalSystemDefinition>().AddAsync(definition, cancellationToken);

    /// <inheritdoc />
    public Task UpdateExternalSystemAsync(ExternalSystemDefinition definition, CancellationToken cancellationToken = default)
    { _context.Set<ExternalSystemDefinition>().Update(definition); return Task.CompletedTask; }

    /// <inheritdoc />
    public async Task DeleteExternalSystemAsync(int id, CancellationToken cancellationToken = default)
    {
        var entity = await GetExternalSystemByIdAsync(id, cancellationToken);
        if (entity != null) _context.Set<ExternalSystemDefinition>().Remove(entity);
    }

    /// <inheritdoc />
    public async Task<ExternalSystemMethod?> GetExternalSystemMethodByIdAsync(int id, CancellationToken cancellationToken = default)
        => await _context.Set<ExternalSystemMethod>().FindAsync(new object[] { id }, cancellationToken);

    /// <inheritdoc />
    // Genuine name-keyed query scoped to the parent system.
    public async Task<ExternalSystemMethod?> GetMethodByNameAsync(int externalSystemId, string methodName, CancellationToken cancellationToken = default)
        => await _context.Set<ExternalSystemMethod>()
            .FirstOrDefaultAsync(
                m => m.ExternalSystemDefinitionId == externalSystemId && m.Name == methodName,
                cancellationToken);

    /// <inheritdoc />
    public async Task<IReadOnlyList<ExternalSystemMethod>> GetMethodsByExternalSystemIdAsync(int externalSystemId, CancellationToken cancellationToken = default)
        => await _context.Set<ExternalSystemMethod>().Where(m => m.ExternalSystemDefinitionId == externalSystemId).ToListAsync(cancellationToken);

    /// <inheritdoc />
    public async Task AddExternalSystemMethodAsync(ExternalSystemMethod method, CancellationToken cancellationToken = default)
        => await _context.Set<ExternalSystemMethod>().AddAsync(method, cancellationToken);

    /// <inheritdoc />
    public Task UpdateExternalSystemMethodAsync(ExternalSystemMethod method, CancellationToken cancellationToken = default)
    { _context.Set<ExternalSystemMethod>().Update(method); return Task.CompletedTask; }

    /// <inheritdoc />
    public async Task DeleteExternalSystemMethodAsync(int id, CancellationToken cancellationToken = default)
    {
        var entity = await GetExternalSystemMethodByIdAsync(id, cancellationToken);
        if (entity != null) _context.Set<ExternalSystemMethod>().Remove(entity);
    }

    /// <inheritdoc />
    public async Task<DatabaseConnectionDefinition?> GetDatabaseConnectionByIdAsync(int id, CancellationToken cancellationToken = default)
        => await _context.Set<DatabaseConnectionDefinition>().FindAsync(new object[] { id }, cancellationToken);

    /// <inheritdoc />
    // Genuine name-keyed query (server-side WHERE).
    public async Task<DatabaseConnectionDefinition?> GetDatabaseConnectionByNameAsync(string name, CancellationToken cancellationToken = default)
        => await _context.Set<DatabaseConnectionDefinition>()
            .FirstOrDefaultAsync(c => c.Name == name, cancellationToken);

    /// <inheritdoc />
    public async Task<IReadOnlyList<DatabaseConnectionDefinition>> GetAllDatabaseConnectionsAsync(CancellationToken cancellationToken = default)
        => await _context.Set<DatabaseConnectionDefinition>().ToListAsync(cancellationToken);

    /// <inheritdoc />
    public async Task AddDatabaseConnectionAsync(DatabaseConnectionDefinition definition, CancellationToken cancellationToken = default)
        => await _context.Set<DatabaseConnectionDefinition>().AddAsync(definition, cancellationToken);

    /// <inheritdoc />
    public Task UpdateDatabaseConnectionAsync(DatabaseConnectionDefinition definition, CancellationToken cancellationToken = default)
    { _context.Set<DatabaseConnectionDefinition>().Update(definition); return Task.CompletedTask; }

    /// <inheritdoc />
    public async Task DeleteDatabaseConnectionAsync(int id, CancellationToken cancellationToken = default)
    {
        var entity = await GetDatabaseConnectionByIdAsync(id, cancellationToken);
        if (entity != null) _context.Set<DatabaseConnectionDefinition>().Remove(entity);
    }

    /// <inheritdoc />
    public async Task<int> SaveChangesAsync(CancellationToken cancellationToken = default)
        => await _context.SaveChangesAsync(cancellationToken);
}
