using e_suite.API.Common;
using e_suite.API.Common.exceptions;
using e_suite.API.Common.models;
using e_suite.Database.Audit;
using e_suite.Service.SigmaImporter.Extensions;

namespace e_suite.Service.SigmaImporter.Helpers;

public class ImportCustomerFieldHelper : IImportCustomFieldHelper
{
    private readonly ICustomFieldManager _customFieldManager;

    public ImportCustomerFieldHelper(ICustomFieldManager customFieldManager)
    {
        _customFieldManager = customFieldManager;
    }

    public async Task EnsureCustomFieldExists(AuditUserDetails auditUserDetails, CreateCustomField customField)
    {
        CustomFieldDefinition? field = null;
        if (customField.Guid.HasValue)
            try
            {
                field ??= await _customFieldManager.GetFieldAsync(customField.Guid.Value.ToGeneralIdRef(),
                    CancellationToken.None);
            }
            catch (NotFoundException)
            {
                field = null;
            }

        try
        {
            field ??= await _customFieldManager.GetFieldAsync(customField.Name, CancellationToken.None);
        }

        catch (NotFoundException)
        {
            field = null;
        }

        if (field == null)
            await _customFieldManager.CreateFieldAsync(auditUserDetails, customField, CancellationToken.None);
    }

    public async Task EnsureCustomFieldsExist(AuditUserDetails auditUserDetails, IEnumerable<CreateCustomField> customFields)
    {
        foreach (var customField in customFields)
        {
            await EnsureCustomFieldExists(auditUserDetails, customField);
        }
    }
}
