@inject ILogger<ImportServiceAliasVault> Logger
@inject NavigationManager NavigationManager
@inject GlobalNotificationService GlobalNotificationService
@inject IStringLocalizerFactory LocalizerFactory
@using AliasVault.ImportExport.Models
@using AliasVault.ImportExport.Importers
@using AliasVault.ImportExport
@using Microsoft.Extensions.Localization
@using System.Text

<ImportServiceCard
    @ref="importServiceCard"
    ServiceName="AliasVault"
    Description="@Localizer["AliasVaultDescription"]"
    LogoUrl="img/logo.svg"
    AcceptedFileExtensions="AcceptedExtensions"
    ProcessFileCallback="ProcessFile">
    <p class="text-gray-700 dark:text-gray-300 mb-4">@Localizer["AliasVaultInstructionsPart1"]</p>
</ImportServiceCard>

@code {
    private IStringLocalizer Localizer => LocalizerFactory.Create("Components.Main.Settings.ImportExport.ImportServices", "AliasVault.Client");
    private static readonly string[] AcceptedExtensions = new[] { ".avex", ".avux", ".csv" };
    private ImportServiceCard? importServiceCard;

    /// <summary>
    /// Processes files with auto-detection based on file extension.
    /// Returns a list of ImportedCredential objects with logos embedded in FaviconBytes.
    /// </summary>
    /// <param name="filename">The name of the uploaded file.</param>
    /// <param name="fileBytes">The file content as bytes.</param>
    /// <returns>A list of ImportedCredential objects.</returns>
    private async Task<ImportFileResult> ProcessFile(string filename, byte[] fileBytes)
    {
        try
        {
            // Detect file format based on extension
            if (filename.EndsWith(".avux", StringComparison.OrdinalIgnoreCase))
            {
                // Process as binary .avux file
                return await VaultImportService.ImportFromAvuxAsync(fileBytes);
            }
            else if (filename.EndsWith(".csv", StringComparison.OrdinalIgnoreCase))
            {
                // Process as text CSV file
                var fileContents = Encoding.UTF8.GetString(fileBytes);
                return await ItemCsvService.ImportItemsFromCsv(fileContents);
            }
            else
            {
                throw new InvalidOperationException($"Unsupported file format: {filename}. Expected .csv or .avux");
            }
        }
        catch (Exception ex)
        {
            throw new InvalidOperationException($"Failed to import file '{filename}': {ex.Message}", ex);
        }
    }
}