using OnlyOneAccessTemplate.Services.OnlyOneAccessTemplate.Services;

namespace OnlyOneAccessTemplate.Services
{
    public class CsvToJsonConverterService : BaseConverterService
    {
        public override string ConverterType => "csv-json";
        public override string ConverterName => "CSV to JSON Converter";

        public CsvToJsonConverterService(ILogger<CsvToJsonConverterService> logger, IConfiguration configuration)
            : base(logger, configuration) { }

        public override async Task<ConversionResult> ConvertAsync(ConversionRequest request)
        {
            try
            {
                string csvContent;

                if (request.InputType == "file" && request.FileInput != null)
                {
                    using var reader = new StreamReader(request.FileInput.OpenReadStream());
                    csvContent = await reader.ReadToEndAsync();
                }
                else if (request.InputType == "text" && !string.IsNullOrEmpty(request.TextInput))
                {
                    csvContent = request.TextInput;
                }
                else
                {
                    return new ConversionResult(false, ErrorMessage: "Nenhum conteúdo CSV fornecido");
                }

                var lines = csvContent.Split('\n', StringSplitOptions.RemoveEmptyEntries);
                if (lines.Length < 2)
                {
                    return new ConversionResult(false, ErrorMessage: "CSV deve ter pelo menos cabeçalho e uma linha de dados");
                }

                var headers = lines[0].Split(',').Select(h => h.Trim().Trim('"')).ToArray();
                var jsonObjects = new List<Dictionary<string, string>>();

                for (int i = 1; i < lines.Length; i++)
                {
                    var values = lines[i].Split(',').Select(v => v.Trim().Trim('"')).ToArray();
                    var obj = new Dictionary<string, string>();

                    for (int j = 0; j < Math.Min(headers.Length, values.Length); j++)
                    {
                        obj[headers[j]] = values[j];
                    }

                    jsonObjects.Add(obj);
                }

                var jsonResult = System.Text.Json.JsonSerializer.Serialize(jsonObjects, new System.Text.Json.JsonSerializerOptions
                {
                    WriteIndented = true,
                    Encoder = System.Text.Encodings.Web.JavaScriptEncoder.UnsafeRelaxedJsonEscaping
                });

                return new ConversionResult(true, OutputText: jsonResult);
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "Erro na conversão CSV para JSON");
                return new ConversionResult(false, ErrorMessage: "Erro ao converter CSV para JSON");
            }
        }

        public override ConverterConfiguration GetConfiguration(string language)
        {
            var texts = GetLocalizedTexts(language);
            texts["ConverterTitle"] = language switch
            {
                "en" => "CSV TO JSON CONVERTER",
                "es" => "CONVERTIDOR CSV A JSON",
                _ => "CONVERSOR CSV PARA JSON"
            };

            texts["ConverterDescription"] = language switch
            {
                "en" => "Convert CSV files to JSON format quickly and easily",
                "es" => "Convierte archivos CSV a formato JSON de forma rápida y fácil",
                _ => "Converta arquivos CSV para formato JSON de forma rápida e fácil"
            };

            texts["InputPlaceholder"] = language switch
            {
                "en" => "Paste your CSV content here or upload a file...",
                "es" => "Pega tu contenido CSV aquí o sube un archivo...",
                _ => "Cole seu conteúdo CSV aqui ou faça upload de um arquivo..."
            };

            texts["FileHelpText"] = language switch
            {
                "en" => "Max file size: 10MB. Supported formats: .csv, .txt",
                "es" => "Tamaño máximo: 10MB. Formatos soportados: .csv, .txt",
                _ => "Tamanho máximo: 10MB. Formatos suportados: .csv, .txt"
            };

            return new ConverterConfiguration
            {
                ConverterType = "text", // Aceita tanto texto quanto arquivo
                OutputType = "text",
                AcceptedFileTypes = new[] { ".csv", ".txt" },
                MaxFileSize = 10 * 1024 * 1024,
                HasAdvancedOptions = false,
                AllowShare = true,
                LocalizedTexts = texts
            };
        }
    }

}
