namespace FKGees.Services;

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

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

    internal async Task Process()
    {
        try
        {
            _logger.LogInformation("DecretsService - Start exports decrets, StartDate: {StartDate}, EndDate: {EndDate}", _context.StatDate , _context.EndDate);
            Console.WriteLine();
            Console.WriteLine("Export dekretów");
            var doctypes = _definitions.Select(x => x.DocType)
                .ToArray();

            var doks = await _pcmService.FetchDecretsDocuments(doctypes, _context.StatDate, _context.EndDate);

            var result = new List<DecretsResult>();
            foreach (var docDefinition in _definitions)
            {
                _logger.LogInformation("DecretsService - Export type: {Type}", docDefinition.Type);
                Console.WriteLine($"Export: {docDefinition.Type}");
                var res = await docDefinition.Process(doks);
                result.AddRange(res);
            }

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