using global::OnlyOneAccessTemplate.Controllers;
using global::OnlyOneAccessTemplate.Services.OnlyOneAccessTemplate.Services;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Caching.Memory;

namespace OnlyOneAccessTemplate.Services
{

    namespace OnlyOneAccessTemplate.Services
    {
        // Interface principal para conversores
        public interface IConverterService
        {
            string ConverterType { get; }
            string ConverterName { get; }
            Task<ConversionResult> ConvertAsync(ConversionRequest request);
            Task<bool> ValidateInputAsync(ConversionRequest request);
            ConverterConfiguration GetConfiguration(string language);
        }

        // Configuração específica do conversor
        public record ConverterConfiguration
        {
            public string ConverterType { get; init; } = "text"; // "text", "file", "url"
            public string OutputType { get; init; } = "text"; // "text", "download", "preview"
            public string[] AcceptedFileTypes { get; init; } = Array.Empty<string>();
            public int MaxFileSize { get; init; } = 10 * 1024 * 1024; // 10MB
            public bool HasAdvancedOptions { get; init; } = false;
            public bool AllowShare { get; init; } = false;
            public Dictionary<string, string> LocalizedTexts { get; init; } = new();
        }

        // Request de conversão
        public record ConversionRequest(
            string Language,
            string InputType, // "text", "file", "url"
            string? TextInput = null,
            IFormFile? FileInput = null,
            string? UrlInput = null,
            Dictionary<string, object>? Options = null
        );

        // Resultado da conversão
        public record ConversionResult(
            bool Success,
            string? OutputText = null,
            byte[]? OutputFile = null,
            string? OutputFileName = null,
            string? OutputMimeType = null,
            string? PreviewHtml = null,
            string? ErrorMessage = null,
            Dictionary<string, object>? Metadata = null
        );

        // Serviço base para conversores
        public abstract class BaseConverterService : IConverterService
        {
            protected readonly ILogger _logger;
            protected readonly IConfiguration _configuration;

            public abstract string ConverterType { get; }
            public abstract string ConverterName { get; }

            protected BaseConverterService(ILogger logger, IConfiguration configuration)
            {
                _logger = logger;
                _configuration = configuration;
            }

            public abstract Task<ConversionResult> ConvertAsync(ConversionRequest request);

            public virtual async Task<bool> ValidateInputAsync(ConversionRequest request)
            {
                var config = GetConfiguration(request.Language);

                // Validação básica baseada no tipo
                switch (request.InputType)
                {
                    case "text":
                        return !string.IsNullOrWhiteSpace(request.TextInput);

                    case "file":
                        if (request.FileInput == null || request.FileInput.Length == 0)
                            return false;

                        // Verificar tamanho do arquivo
                        if (request.FileInput.Length > config.MaxFileSize)
                            return false;

                        // Verificar tipo do arquivo se especificado
                        if (config.AcceptedFileTypes.Length > 0)
                        {
                            var extension = Path.GetExtension(request.FileInput.FileName);
                            return config.AcceptedFileTypes.Contains(extension, StringComparer.OrdinalIgnoreCase);
                        }
                        return true;

                    case "url":
                        return Uri.TryCreate(request.UrlInput, UriKind.Absolute, out _);

                    default:
                        return false;
                }
            }

            public abstract ConverterConfiguration GetConfiguration(string language);

            protected virtual Dictionary<string, string> GetLocalizedTexts(string language)
            {
                return language switch
                {
                    "en" => GetEnglishTexts(),
                    "es" => GetSpanishTexts(),
                    _ => GetPortugueseTexts()
                };
            }

            protected virtual Dictionary<string, string> GetPortugueseTexts()
            {
                return new Dictionary<string, string>
                {
                    ["ConverterTitle"] = "CONVERSOR ONLINE",
                    ["ConverterDescription"] = "Converta seus arquivos de forma rápida e segura",
                    ["Step1Title"] = "Upload",
                    ["Step1Description"] = "Selecione ou cole seu conteúdo",
                    ["Step2Title"] = "Configurar",
                    ["Step2Description"] = "Escolha as opções de conversão",
                    ["Step3Title"] = "Converter",
                    ["Step3Description"] = "Baixe o resultado",
                    ["InputLabel"] = "Entrada",
                    ["OutputLabel"] = "Resultado",
                    ["SelectFileText"] = "Selecionar Arquivo",
                    ["ConvertButtonText"] = "Converter",
                    ["LoadingText"] = "Processando...",
                    ["ProcessingText"] = "Convertendo seu arquivo...",
                    ["CopyButtonText"] = "Copiar",
                    ["ClearButtonText"] = "Limpar",
                    ["ShareButtonText"] = "Compartilhar",
                    ["CopiedText"] = "Copiado!",
                    ["DownloadButtonText"] = "Baixar",
                    ["DownloadReadyText"] = "Seu arquivo está pronto!",
                    ["SecurityText"] = "Seus dados estão seguros conosco",
                    ["DefaultErrorMessage"] = "Erro ao processar. Tente novamente."
                };
            }

            protected virtual Dictionary<string, string> GetEnglishTexts()
            {
                return new Dictionary<string, string>
                {
                    ["ConverterTitle"] = "ONLINE CONVERTER",
                    ["ConverterDescription"] = "Convert your files quickly and securely",
                    ["Step1Title"] = "Upload",
                    ["Step1Description"] = "Select or paste your content",
                    ["Step2Title"] = "Configure",
                    ["Step2Description"] = "Choose conversion options",
                    ["Step3Title"] = "Convert",
                    ["Step3Description"] = "Download the result",
                    ["InputLabel"] = "Input",
                    ["OutputLabel"] = "Output",
                    ["SelectFileText"] = "Select File",
                    ["ConvertButtonText"] = "Convert",
                    ["LoadingText"] = "Processing...",
                    ["ProcessingText"] = "Converting your file...",
                    ["CopyButtonText"] = "Copy",
                    ["ClearButtonText"] = "Clear",
                    ["ShareButtonText"] = "Share",
                    ["CopiedText"] = "Copied!",
                    ["DownloadButtonText"] = "Download",
                    ["DownloadReadyText"] = "Your file is ready!",
                    ["SecurityText"] = "Your data is safe with us",
                    ["DefaultErrorMessage"] = "Processing error. Please try again."
                };
            }

            protected virtual Dictionary<string, string> GetSpanishTexts()
            {
                return new Dictionary<string, string>
                {
                    ["ConverterTitle"] = "CONVERTIDOR EN LÍNEA",
                    ["ConverterDescription"] = "Convierte tus archivos de forma rápida y segura",
                    ["Step1Title"] = "Subir",
                    ["Step1Description"] = "Selecciona o pega tu contenido",
                    ["Step2Title"] = "Configurar",
                    ["Step2Description"] = "Elige las opciones de conversión",
                    ["Step3Title"] = "Convertir",
                    ["Step3Description"] = "Descarga el resultado",
                    ["InputLabel"] = "Entrada",
                    ["OutputLabel"] = "Resultado",
                    ["SelectFileText"] = "Seleccionar Archivo",
                    ["ConvertButtonText"] = "Convertir",
                    ["LoadingText"] = "Procesando...",
                    ["ProcessingText"] = "Convirtiendo tu archivo...",
                    ["CopyButtonText"] = "Copiar",
                    ["ClearButtonText"] = "Limpiar",
                    ["ShareButtonText"] = "Compartir",
                    ["CopiedText"] = "¡Copiado!",
                    ["DownloadButtonText"] = "Descargar",
                    ["DownloadReadyText"] = "¡Tu archivo está listo!",
                    ["SecurityText"] = "Tus datos están seguros con nosotros",
                    ["DefaultErrorMessage"] = "Error al procesar. Inténtalo de nuevo."
                };
            }
        }
    }
}
