using Microsoft.EntityFrameworkCore;
using ScadaLink.Commons.Entities.Instances;
using ScadaLink.Commons.Entities.Sites;
using ScadaLink.Commons.Interfaces.Repositories;

namespace ScadaLink.ConfigurationDatabase.Repositories;

/// <summary>
/// EF Core implementation of ISiteRepository for site and data connection management.
/// </summary>
public class SiteRepository : ISiteRepository
{
    private readonly ScadaLinkDbContext _dbContext;

    public SiteRepository(ScadaLinkDbContext dbContext)
    {
        _dbContext = dbContext ?? throw new ArgumentNullException(nameof(dbContext));
    }

    // --- Sites ---

    public async Task<Site?> GetSiteByIdAsync(int id, CancellationToken cancellationToken = default)
    {
        return await _dbContext.Sites.FindAsync([id], cancellationToken);
    }

    public async Task<Site?> GetSiteByIdentifierAsync(string siteIdentifier, CancellationToken cancellationToken = default)
    {
        return await _dbContext.Sites
            .FirstOrDefaultAsync(s => s.SiteIdentifier == siteIdentifier, cancellationToken);
    }

    public async Task<IReadOnlyList<Site>> GetAllSitesAsync(CancellationToken cancellationToken = default)
    {
        return await _dbContext.Sites.OrderBy(s => s.Name).ToListAsync(cancellationToken);
    }

    public async Task AddSiteAsync(Site site, CancellationToken cancellationToken = default)
    {
        await _dbContext.Sites.AddAsync(site, cancellationToken);
    }

    public Task UpdateSiteAsync(Site site, CancellationToken cancellationToken = default)
    {
        _dbContext.Sites.Update(site);
        return Task.CompletedTask;
    }

    public Task DeleteSiteAsync(int id, CancellationToken cancellationToken = default)
    {
        var entity = _dbContext.Sites.Local.FirstOrDefault(s => s.Id == id);
        if (entity != null)
        {
            _dbContext.Sites.Remove(entity);
        }
        else
        {
            var stub = new Site("stub", "stub") { Id = id };
            _dbContext.Sites.Attach(stub);
            _dbContext.Sites.Remove(stub);
        }
        return Task.CompletedTask;
    }

    // --- Data Connections ---

    public async Task<DataConnection?> GetDataConnectionByIdAsync(int id, CancellationToken cancellationToken = default)
    {
        return await _dbContext.DataConnections.FindAsync([id], cancellationToken);
    }

    public async Task<IReadOnlyList<DataConnection>> GetAllDataConnectionsAsync(CancellationToken cancellationToken = default)
    {
        return await _dbContext.DataConnections.OrderBy(c => c.Name).ToListAsync(cancellationToken);
    }

    public async Task<IReadOnlyList<DataConnection>> GetDataConnectionsBySiteIdAsync(int siteId, CancellationToken cancellationToken = default)
    {
        return await _dbContext.DataConnections
            .Where(c => c.SiteId == siteId)
            .OrderBy(c => c.Name)
            .ToListAsync(cancellationToken);
    }

    public async Task AddDataConnectionAsync(DataConnection connection, CancellationToken cancellationToken = default)
    {
        await _dbContext.DataConnections.AddAsync(connection, cancellationToken);
    }

    public Task UpdateDataConnectionAsync(DataConnection connection, CancellationToken cancellationToken = default)
    {
        _dbContext.DataConnections.Update(connection);
        return Task.CompletedTask;
    }

    public Task DeleteDataConnectionAsync(int id, CancellationToken cancellationToken = default)
    {
        var entity = _dbContext.DataConnections.Local.FirstOrDefault(c => c.Id == id);
        if (entity != null)
        {
            _dbContext.DataConnections.Remove(entity);
        }
        else
        {
            var stub = new DataConnection("stub", "stub", 0) { Id = id };
            _dbContext.DataConnections.Attach(stub);
            _dbContext.DataConnections.Remove(stub);
        }
        return Task.CompletedTask;
    }

    // --- Instances (for deletion constraint checks) ---

    public async Task<IReadOnlyList<Instance>> GetInstancesBySiteIdAsync(int siteId, CancellationToken cancellationToken = default)
    {
        return await _dbContext.Instances
            .Where(i => i.SiteId == siteId)
            .ToListAsync(cancellationToken);
    }

    public async Task<int> SaveChangesAsync(CancellationToken cancellationToken = default)
    {
        return await _dbContext.SaveChangesAsync(cancellationToken);
    }
}
