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

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

public class InboundApiRepository : IInboundApiRepository
{
    private readonly ScadaBridgeDbContext _context;

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

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

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

    /// <inheritdoc />
    public async Task<ApiMethod?> GetMethodByNameAsync(string name, CancellationToken cancellationToken = default)
        => await _context.Set<ApiMethod>().FirstOrDefaultAsync(m => m.Name == name, cancellationToken);

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

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

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

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