using Microsoft.EntityFrameworkCore;
using ScadaLink.Commons.Entities.Instances;
using ScadaLink.Commons.Entities.Scripts;
using ScadaLink.Commons.Entities.Templates;
using ScadaLink.Commons.Interfaces.Repositories;

namespace ScadaLink.ConfigurationDatabase.Repositories;

public class TemplateEngineRepository : ITemplateEngineRepository
{
    private readonly ScadaLinkDbContext _context;

    public TemplateEngineRepository(ScadaLinkDbContext context)
    {
        _context = context ?? throw new ArgumentNullException(nameof(context));
    }

    // Template

    public async Task<Template?> GetTemplateByIdAsync(int id, CancellationToken cancellationToken = default)
    {
        return await _context.Templates
            .Include(t => t.Attributes)
            .Include(t => t.Alarms)
            .Include(t => t.Scripts)
            .Include(t => t.Compositions)
            .FirstOrDefaultAsync(t => t.Id == id, cancellationToken);
    }

    /// <summary>
    /// Loads a template together with its child members — Attributes, Alarms,
    /// Scripts and Compositions — eager-loaded so callers get the full template
    /// aggregate in a single round-trip. "Children" here refers to the template's
    /// member collections, not derived/sub templates.
    /// </summary>
    public async Task<Template?> GetTemplateWithChildrenAsync(int id, CancellationToken cancellationToken = default)
    {
        return await GetTemplateByIdAsync(id, cancellationToken);
    }

    public async Task<IReadOnlyList<Template>> GetAllTemplatesAsync(CancellationToken cancellationToken = default)
    {
        return await _context.Templates
            .Include(t => t.Attributes)
            .Include(t => t.Alarms)
            .Include(t => t.Scripts)
            .Include(t => t.Compositions)
            .ToListAsync(cancellationToken);
    }

    public async Task<IReadOnlyList<Template>> GetTemplatesComposingAsync(int composedTemplateId, CancellationToken cancellationToken = default)
    {
        return await _context.Templates
            .Where(t => t.Compositions.Any(c => c.ComposedTemplateId == composedTemplateId))
            .Include(t => t.Attributes)
            .Include(t => t.Scripts)
            .Include(t => t.Compositions)
            .ToListAsync(cancellationToken);
    }

    public async Task AddTemplateAsync(Template template, CancellationToken cancellationToken = default)
    {
        await _context.Templates.AddAsync(template, cancellationToken);
    }

    public Task UpdateTemplateAsync(Template template, CancellationToken cancellationToken = default)
    {
        _context.Templates.Update(template);
        return Task.CompletedTask;
    }

    public async Task DeleteTemplateAsync(int id, CancellationToken cancellationToken = default)
    {
        var template = await _context.Templates.FindAsync(new object[] { id }, cancellationToken);
        if (template != null)
        {
            _context.Templates.Remove(template);
        }
    }

    // TemplateAttribute

    public async Task<TemplateAttribute?> GetTemplateAttributeByIdAsync(int id, CancellationToken cancellationToken = default)
    {
        return await _context.TemplateAttributes.FindAsync(new object[] { id }, cancellationToken);
    }

    public async Task<IReadOnlyList<TemplateAttribute>> GetAttributesByTemplateIdAsync(int templateId, CancellationToken cancellationToken = default)
    {
        return await _context.TemplateAttributes
            .Where(a => a.TemplateId == templateId)
            .ToListAsync(cancellationToken);
    }

    public async Task AddTemplateAttributeAsync(TemplateAttribute attribute, CancellationToken cancellationToken = default)
    {
        await _context.TemplateAttributes.AddAsync(attribute, cancellationToken);
    }

    public Task UpdateTemplateAttributeAsync(TemplateAttribute attribute, CancellationToken cancellationToken = default)
    {
        _context.TemplateAttributes.Update(attribute);
        return Task.CompletedTask;
    }

    public async Task DeleteTemplateAttributeAsync(int id, CancellationToken cancellationToken = default)
    {
        var attribute = await _context.TemplateAttributes.FindAsync(new object[] { id }, cancellationToken);
        if (attribute != null)
        {
            _context.TemplateAttributes.Remove(attribute);
        }
    }

    // TemplateAlarm

    public async Task<TemplateAlarm?> GetTemplateAlarmByIdAsync(int id, CancellationToken cancellationToken = default)
    {
        return await _context.TemplateAlarms.FindAsync(new object[] { id }, cancellationToken);
    }

    public async Task<IReadOnlyList<TemplateAlarm>> GetAlarmsByTemplateIdAsync(int templateId, CancellationToken cancellationToken = default)
    {
        return await _context.TemplateAlarms
            .Where(a => a.TemplateId == templateId)
            .ToListAsync(cancellationToken);
    }

    public async Task AddTemplateAlarmAsync(TemplateAlarm alarm, CancellationToken cancellationToken = default)
    {
        await _context.TemplateAlarms.AddAsync(alarm, cancellationToken);
    }

    public Task UpdateTemplateAlarmAsync(TemplateAlarm alarm, CancellationToken cancellationToken = default)
    {
        _context.TemplateAlarms.Update(alarm);
        return Task.CompletedTask;
    }

    public async Task DeleteTemplateAlarmAsync(int id, CancellationToken cancellationToken = default)
    {
        var alarm = await _context.TemplateAlarms.FindAsync(new object[] { id }, cancellationToken);
        if (alarm != null)
        {
            _context.TemplateAlarms.Remove(alarm);
        }
    }

    // TemplateScript

    public async Task<TemplateScript?> GetTemplateScriptByIdAsync(int id, CancellationToken cancellationToken = default)
    {
        return await _context.TemplateScripts.FindAsync(new object[] { id }, cancellationToken);
    }

    public async Task<IReadOnlyList<TemplateScript>> GetScriptsByTemplateIdAsync(int templateId, CancellationToken cancellationToken = default)
    {
        return await _context.TemplateScripts
            .Where(s => s.TemplateId == templateId)
            .ToListAsync(cancellationToken);
    }

    public async Task AddTemplateScriptAsync(TemplateScript script, CancellationToken cancellationToken = default)
    {
        await _context.TemplateScripts.AddAsync(script, cancellationToken);
    }

    public Task UpdateTemplateScriptAsync(TemplateScript script, CancellationToken cancellationToken = default)
    {
        _context.TemplateScripts.Update(script);
        return Task.CompletedTask;
    }

    public async Task DeleteTemplateScriptAsync(int id, CancellationToken cancellationToken = default)
    {
        var script = await _context.TemplateScripts.FindAsync(new object[] { id }, cancellationToken);
        if (script != null)
        {
            _context.TemplateScripts.Remove(script);
        }
    }

    // TemplateComposition

    public async Task<TemplateComposition?> GetTemplateCompositionByIdAsync(int id, CancellationToken cancellationToken = default)
    {
        return await _context.TemplateCompositions.FindAsync(new object[] { id }, cancellationToken);
    }

    public async Task<IReadOnlyList<TemplateComposition>> GetCompositionsByTemplateIdAsync(int templateId, CancellationToken cancellationToken = default)
    {
        return await _context.TemplateCompositions
            .Where(c => c.TemplateId == templateId)
            .ToListAsync(cancellationToken);
    }

    public async Task AddTemplateCompositionAsync(TemplateComposition composition, CancellationToken cancellationToken = default)
    {
        await _context.TemplateCompositions.AddAsync(composition, cancellationToken);
    }

    public Task UpdateTemplateCompositionAsync(TemplateComposition composition, CancellationToken cancellationToken = default)
    {
        _context.TemplateCompositions.Update(composition);
        return Task.CompletedTask;
    }

    public async Task DeleteTemplateCompositionAsync(int id, CancellationToken cancellationToken = default)
    {
        var composition = await _context.TemplateCompositions.FindAsync(new object[] { id }, cancellationToken);
        if (composition != null)
        {
            _context.TemplateCompositions.Remove(composition);
        }
    }

    // Instance

    public async Task<Instance?> GetInstanceByIdAsync(int id, CancellationToken cancellationToken = default)
    {
        return await _context.Instances
            .Include(i => i.AttributeOverrides)
            .Include(i => i.AlarmOverrides)
            .Include(i => i.ConnectionBindings)
            .FirstOrDefaultAsync(i => i.Id == id, cancellationToken);
    }

    public async Task<IReadOnlyList<Instance>> GetAllInstancesAsync(CancellationToken cancellationToken = default)
    {
        return await _context.Instances
            .Include(i => i.AttributeOverrides)
            .Include(i => i.AlarmOverrides)
            .Include(i => i.ConnectionBindings)
            .ToListAsync(cancellationToken);
    }

    public async Task<IReadOnlyList<Instance>> GetInstancesByTemplateIdAsync(int templateId, CancellationToken cancellationToken = default)
    {
        return await _context.Instances
            .Where(i => i.TemplateId == templateId)
            .ToListAsync(cancellationToken);
    }

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

    public async Task<Instance?> GetInstanceByUniqueNameAsync(string uniqueName, CancellationToken cancellationToken = default)
    {
        return await _context.Instances
            .Include(i => i.AttributeOverrides)
            .Include(i => i.AlarmOverrides)
            .Include(i => i.ConnectionBindings)
            .FirstOrDefaultAsync(i => i.UniqueName == uniqueName, cancellationToken);
    }

    public async Task AddInstanceAsync(Instance instance, CancellationToken cancellationToken = default)
    {
        await _context.Instances.AddAsync(instance, cancellationToken);
    }

    public Task UpdateInstanceAsync(Instance instance, CancellationToken cancellationToken = default)
    {
        _context.Instances.Update(instance);
        return Task.CompletedTask;
    }

    public async Task DeleteInstanceAsync(int id, CancellationToken cancellationToken = default)
    {
        var instance = await _context.Instances.FindAsync(new object[] { id }, cancellationToken);
        if (instance != null)
        {
            _context.Instances.Remove(instance);
        }
    }

    // InstanceAttributeOverride

    public async Task<IReadOnlyList<InstanceAttributeOverride>> GetOverridesByInstanceIdAsync(int instanceId, CancellationToken cancellationToken = default)
    {
        return await _context.InstanceAttributeOverrides
            .Where(o => o.InstanceId == instanceId)
            .ToListAsync(cancellationToken);
    }

    public async Task AddInstanceAttributeOverrideAsync(InstanceAttributeOverride attributeOverride, CancellationToken cancellationToken = default)
    {
        await _context.InstanceAttributeOverrides.AddAsync(attributeOverride, cancellationToken);
    }

    public Task UpdateInstanceAttributeOverrideAsync(InstanceAttributeOverride attributeOverride, CancellationToken cancellationToken = default)
    {
        _context.InstanceAttributeOverrides.Update(attributeOverride);
        return Task.CompletedTask;
    }

    public async Task DeleteInstanceAttributeOverrideAsync(int id, CancellationToken cancellationToken = default)
    {
        var attributeOverride = await _context.InstanceAttributeOverrides.FindAsync(new object[] { id }, cancellationToken);
        if (attributeOverride != null)
        {
            _context.InstanceAttributeOverrides.Remove(attributeOverride);
        }
    }

    // InstanceAlarmOverride

    public async Task<IReadOnlyList<InstanceAlarmOverride>> GetAlarmOverridesByInstanceIdAsync(int instanceId, CancellationToken cancellationToken = default)
    {
        return await _context.InstanceAlarmOverrides
            .Where(o => o.InstanceId == instanceId)
            .ToListAsync(cancellationToken);
    }

    public async Task<InstanceAlarmOverride?> GetAlarmOverrideAsync(int instanceId, string alarmCanonicalName, CancellationToken cancellationToken = default)
    {
        return await _context.InstanceAlarmOverrides
            .FirstOrDefaultAsync(
                o => o.InstanceId == instanceId && o.AlarmCanonicalName == alarmCanonicalName,
                cancellationToken);
    }

    public async Task AddInstanceAlarmOverrideAsync(InstanceAlarmOverride alarmOverride, CancellationToken cancellationToken = default)
    {
        await _context.InstanceAlarmOverrides.AddAsync(alarmOverride, cancellationToken);
    }

    public Task UpdateInstanceAlarmOverrideAsync(InstanceAlarmOverride alarmOverride, CancellationToken cancellationToken = default)
    {
        _context.InstanceAlarmOverrides.Update(alarmOverride);
        return Task.CompletedTask;
    }

    public async Task DeleteInstanceAlarmOverrideAsync(int id, CancellationToken cancellationToken = default)
    {
        var alarmOverride = await _context.InstanceAlarmOverrides.FindAsync(new object[] { id }, cancellationToken);
        if (alarmOverride != null)
        {
            _context.InstanceAlarmOverrides.Remove(alarmOverride);
        }
    }

    // InstanceConnectionBinding

    public async Task<IReadOnlyList<InstanceConnectionBinding>> GetBindingsByInstanceIdAsync(int instanceId, CancellationToken cancellationToken = default)
    {
        return await _context.InstanceConnectionBindings
            .Where(b => b.InstanceId == instanceId)
            .ToListAsync(cancellationToken);
    }

    public async Task AddInstanceConnectionBindingAsync(InstanceConnectionBinding binding, CancellationToken cancellationToken = default)
    {
        await _context.InstanceConnectionBindings.AddAsync(binding, cancellationToken);
    }

    public Task UpdateInstanceConnectionBindingAsync(InstanceConnectionBinding binding, CancellationToken cancellationToken = default)
    {
        _context.InstanceConnectionBindings.Update(binding);
        return Task.CompletedTask;
    }

    public async Task DeleteInstanceConnectionBindingAsync(int id, CancellationToken cancellationToken = default)
    {
        var binding = await _context.InstanceConnectionBindings.FindAsync(new object[] { id }, cancellationToken);
        if (binding != null)
        {
            _context.InstanceConnectionBindings.Remove(binding);
        }
    }

    // Area

    public async Task<Area?> GetAreaByIdAsync(int id, CancellationToken cancellationToken = default)
    {
        return await _context.Areas
            .Include(a => a.Children)
            .FirstOrDefaultAsync(a => a.Id == id, cancellationToken);
    }

    public async Task<IReadOnlyList<Area>> GetAreasBySiteIdAsync(int siteId, CancellationToken cancellationToken = default)
    {
        return await _context.Areas
            .Where(a => a.SiteId == siteId)
            .Include(a => a.Children)
            .ToListAsync(cancellationToken);
    }

    public async Task AddAreaAsync(Area area, CancellationToken cancellationToken = default)
    {
        await _context.Areas.AddAsync(area, cancellationToken);
    }

    public Task UpdateAreaAsync(Area area, CancellationToken cancellationToken = default)
    {
        _context.Areas.Update(area);
        return Task.CompletedTask;
    }

    public async Task DeleteAreaAsync(int id, CancellationToken cancellationToken = default)
    {
        var area = await _context.Areas.FindAsync(new object[] { id }, cancellationToken);
        if (area != null)
        {
            _context.Areas.Remove(area);
        }
    }

    // SharedScript

    public async Task<SharedScript?> GetSharedScriptByIdAsync(int id, CancellationToken cancellationToken = default)
    {
        return await _context.SharedScripts.FindAsync(new object[] { id }, cancellationToken);
    }

    public async Task<SharedScript?> GetSharedScriptByNameAsync(string name, CancellationToken cancellationToken = default)
    {
        return await _context.SharedScripts
            .FirstOrDefaultAsync(s => s.Name == name, cancellationToken);
    }

    public async Task<IReadOnlyList<SharedScript>> GetAllSharedScriptsAsync(CancellationToken cancellationToken = default)
    {
        return await _context.SharedScripts.ToListAsync(cancellationToken);
    }

    public async Task AddSharedScriptAsync(SharedScript sharedScript, CancellationToken cancellationToken = default)
    {
        await _context.SharedScripts.AddAsync(sharedScript, cancellationToken);
    }

    public Task UpdateSharedScriptAsync(SharedScript sharedScript, CancellationToken cancellationToken = default)
    {
        _context.SharedScripts.Update(sharedScript);
        return Task.CompletedTask;
    }

    public async Task DeleteSharedScriptAsync(int id, CancellationToken cancellationToken = default)
    {
        var sharedScript = await _context.SharedScripts.FindAsync(new object[] { id }, cancellationToken);
        if (sharedScript != null)
        {
            _context.SharedScripts.Remove(sharedScript);
        }
    }

    // TemplateFolder

    public async Task<TemplateFolder?> GetFolderByIdAsync(int id, CancellationToken cancellationToken = default)
        => await _context.TemplateFolders.FindAsync(new object[] { id }, cancellationToken);

    public async Task<IReadOnlyList<TemplateFolder>> GetAllFoldersAsync(CancellationToken cancellationToken = default)
        => await _context.TemplateFolders.ToListAsync(cancellationToken);

    public async Task AddFolderAsync(TemplateFolder folder, CancellationToken cancellationToken = default)
        => await _context.TemplateFolders.AddAsync(folder, cancellationToken);

    public Task UpdateFolderAsync(TemplateFolder folder, CancellationToken cancellationToken = default)
    {
        _context.TemplateFolders.Update(folder);
        return Task.CompletedTask;
    }

    public async Task DeleteFolderAsync(int id, CancellationToken cancellationToken = default)
    {
        var folder = await _context.TemplateFolders.FindAsync(new object[] { id }, cancellationToken);
        if (folder != null)
        {
            _context.TemplateFolders.Remove(folder);
        }
    }

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