using IWS5.DatabaseAccess.Interfaces.Importer;
using IWS5.DatabaseAccess.IwsDataContext;
using Microsoft.EntityFrameworkCore;
using IWS5.Importer.Abstractions.DTO;

namespace IWS5.DatabaseAccess.Repositories.Importer;

public class ProcessImportRuleRepository(IDbContextFactory<GreenfieldPd2015Context> contextFactory)
    : IProcessImportRuleRepository
{
    public async Task<ProcessImportRuleDto?> GetProcessImportRuleAsync(int processId)
    {
        await using var context = await contextFactory.CreateDbContextAsync();
        var rule = await context.AtprocessImportRules.FirstOrDefaultAsync(r => r.ProcessId == processId);

        if (rule == null) return null;

        return new ProcessImportRuleDto
        {
            ProcessId = rule.ProcessId,
            DoNotConvert = rule.DoNotConvert
                .Split(';', StringSplitOptions.RemoveEmptyEntries)
                .Select(x => x.Trim().ToLowerInvariant())
                .ToList(),
            MergeDocuments = rule.MergeDocuments,
            ConvertToFormatId = rule.ConvertToFormatId,
            RenameWhenMerged = rule.RenameWhenMerged
        };
    }
}
