using e_suite.API.Common;
using e_suite.API.Common.exceptions;
using e_suite.API.Common.models;
using e_suite.Database.Audit;
using eSuite.Core.Miscellaneous;

namespace e_suite.Service.SigmaImporter.Helpers;

public class ImportGlossaryHelper : IImportGlossaryHelper
{
    private readonly IGlossariesManager _glossariesManager;

    public ImportGlossaryHelper(IGlossariesManager glossariesManager)
    {
        _glossariesManager = glossariesManager;
    }

    public GeneralIdRef SystemGlossaryGeneralIdRef { get; } = new()
    {
        Guid = new Guid("FA6566F8-B4B0-48C5-9985-336C9284796E")
    };

    public GeneralIdRef PrintSpecificationGlossaryGeneralIdRef { get; } = new()
    {
        Guid = new Guid("35EB8C23-4528-49A7-A798-B8BAE3B06DAF")
    };
    
    public async Task<GlossaryItem> EnsureGlossaryItemExists(AuditUserDetails auditUserDetails, NewGlossaryItem glossary)
    {
        var glossaryGeneralIdRef = new GeneralIdRef
        {
            Guid = glossary.Guid
        };

        GlossaryItem? glossaryItem;
        try
        {
            glossaryItem = await _glossariesManager.GetGlossaryItem(auditUserDetails, glossaryGeneralIdRef, CancellationToken.None);
        }
        catch (NotFoundException)
        {
            await _glossariesManager.AddGlossaryItem(auditUserDetails, glossary, CancellationToken.None);
            glossaryItem = await _glossariesManager.GetGlossaryItem(auditUserDetails, glossaryGeneralIdRef, CancellationToken.None);
        }

        return glossaryItem!;
    }

    public async Task EnsureGlossaryItemsExists(AuditUserDetails auditUserDetails, IEnumerable<NewGlossaryItem> glossaryItems)
    {
        foreach (var glossaryItem in glossaryItems)
        {
            await EnsureGlossaryItemExists(auditUserDetails, glossaryItem);
        }
    }
    
}