namespace FKGees.Services;

internal class RegistersService
{
    private readonly PcmService _pcmService;
    private readonly CsvService _csvService;
    private readonly IEnumerable<IRegistersDefinition> _definitions;
    private readonly ILogger<DecretsService> _logger;
    private readonly Context _context;

    public RegistersService(PcmService pcmService, CsvService csvService, IEnumerable<IRegistersDefinition> definitions,
        ILogger<DecretsService> logger, Context context)
    {
        _pcmService = pcmService;
        _csvService = csvService;
        _definitions = definitions;
        _logger = logger;
        _context = context;
    }

    public async Task Process()
    {
        try
        {
            _logger.LogInformation("RegistersService - Start exports registers, StartDate: {StartDate}, EndDate: {EndDate}", _context.StatDate , _context.EndDate);
            Console.WriteLine();
            Console.WriteLine("Export rejestrów");

            var result = new List<RegistersResult>();

            foreach (var definition in _definitions)
            {
                _logger.LogInformation("RegistersService - Export type: {Type}", definition.Type);
                Console.WriteLine($"Export: {definition.Type}");
                var docs = await _pcmService.FetchRegistersDocuments(definition.DocTypes, _context.StatDate, _context.EndDate);
                result.AddRange(await definition.Process(docs));
            }

            _logger.LogInformation("RegistersService - Export success");
            Console.WriteLine("Eksport do pliku rejestrów");
            Console.WriteLine();
            await _csvService.CsvExport($"Export/{_context.RegistersFileName}", result.OrderBy(x => x.dwystawienia));
            Console.WriteLine("Eksport do pliku rejestrów zakończony powodzeniem");
        }
        catch (Exception e)
        {
            _logger.LogError(e, "RegistersService - Export failed");
            Console.WriteLine("Eksport do pliku rejestrów zakończony niepowodzeniem");
            Console.WriteLine(e.Message);
            throw;
        }
    }
}