namespace MBN_STOCK_WEBVIEW.LegacyWeb.Tests;

public sealed class LegacyComparisonImportWebTests
{
    private static readonly string RepositoryRoot = FindRepositoryRoot();
    private static readonly string App = Read("src", "MBN_STOCK_WEBVIEW.LegacyParityApp", "Web", "app.js");
    private static readonly string Styles = Read("src", "MBN_STOCK_WEBVIEW.LegacyParityApp", "Web", "styles.css");
    private static readonly string MainWindow = Read("src", "MBN_STOCK_WEBVIEW.LegacyParityApp", "MainWindow.xaml.cs");
    private static readonly string Bridge = Read("src", "MBN_STOCK_WEBVIEW.LegacyBridge", "LegacyBridgeProtocol.cs");

    [Fact]
    public void Comparison_workspace_exposes_explicit_fixed_source_merge_and_result()
    {
        Assert.Contains("importLegacy.textContent = \"원본 비교쌍 가져오기\"", App,
            StringComparison.Ordinal);
        Assert.Contains("importLegacy.dataset.comparisonImport = \"true\"", App,
            StringComparison.Ordinal);
        Assert.Contains("send(\"import-legacy-comparison-pairs\", {})", App,
            StringComparison.Ordinal);
        Assert.Contains("comparison.lastImport.sourceRowCount", App,
            StringComparison.Ordinal);
        Assert.Contains("comparison.lastImport.addedPairCount", App,
            StringComparison.Ordinal);
        Assert.Contains(".comparison-import-status", Styles, StringComparison.Ordinal);
        Assert.DoesNotContain("comparisonImportPath", App, StringComparison.Ordinal);
    }

    [Fact]
    public void Native_composition_owns_the_trusted_source_and_database_resolver()
    {
        Assert.Contains("TrustedLegacyComparisonFileSource.CreateDefault()", MainWindow,
            StringComparison.Ordinal);
        Assert.Contains("new LegacyComparisonPairImportService(", MainWindow,
            StringComparison.Ordinal);
        Assert.Contains("comparisonImporter)", MainWindow, StringComparison.Ordinal);
        Assert.Contains("\"import-legacy-comparison-pairs\" => ParseComparisonImport(payload)",
            Bridge, StringComparison.Ordinal);
        Assert.Contains("HasOnlyProperties(payload) ? new LegacyImportComparisonPairsIntent()",
            Bridge, StringComparison.Ordinal);
    }

    private static string Read(params string[] segments) =>
        File.ReadAllText(Path.Combine([RepositoryRoot, .. segments]));

    private static string FindRepositoryRoot()
    {
        var directory = new DirectoryInfo(AppContext.BaseDirectory);
        while (directory is not null)
        {
            if (File.Exists(Path.Combine(directory.FullName, "MBN_STOCK_WEBVIEW.sln")))
            {
                return directory.FullName;
            }

            directory = directory.Parent;
        }

        throw new DirectoryNotFoundException("Repository root was not found.");
    }
}
