namespace MBN_STOCK_WEBVIEW.LegacyWeb.Tests;

public sealed class LegacyCloseConfirmationNativeContractTests
{
    private static readonly string RepositoryRoot = FindRepositoryRoot();
    private static readonly string AppRoot = Path.Combine(
        RepositoryRoot,
        "src",
        "MBN_STOCK_WEBVIEW.LegacyParityApp");
    private static readonly string Window = File.ReadAllText(
        Path.Combine(AppRoot, "MainWindow.xaml.cs"));
    private static readonly string Confirmation = File.ReadAllText(
        Path.Combine(AppRoot, "MainWindow.CloseConfirmation.cs"));

    [Fact]
    public void SystemCloseRequiresExplicitDefaultCancelConfirmation()
    {
        Assert.Contains("EnsureCloseConfirmationAttached();", Window,
            StringComparison.Ordinal);
        Assert.Contains("appWindow.Closing += OnAppWindowClosing", Confirmation,
            StringComparison.Ordinal);
        Assert.Contains("args.Cancel = true", Confirmation, StringComparison.Ordinal);
        Assert.Contains("DefaultButton = ContentDialogButton.Close", Confirmation,
            StringComparison.Ordinal);
        Assert.Contains("Title = \"매일경제TV\"", Confirmation,
            StringComparison.Ordinal);
        Assert.Contains("PrimaryButtonText = \"예\"", Confirmation,
            StringComparison.Ordinal);
        Assert.Contains("CloseButtonText = \"아니요\"", Confirmation,
            StringComparison.Ordinal);
        Assert.Contains("Interlocked.Exchange(ref _closeConfirmed, 1);", Confirmation,
            StringComparison.Ordinal);
        Assert.Contains("DetachCloseConfirmation();", Window, StringComparison.Ordinal);
    }

    [Fact]
    public void ClosingNeverInventsAnAutomaticPlayoutCommand()
    {
        Assert.Contains("종료 과정에서는 TAKE OUT을 자동 실행하지 않습니다", Confirmation,
            StringComparison.Ordinal);
        Assert.DoesNotContain("TakeOutAsync", Confirmation, StringComparison.Ordinal);
        Assert.DoesNotContain("StopAll", Confirmation, StringComparison.Ordinal);
        Assert.DoesNotContain("ExecuteOperatorPlayoutAsync", Confirmation,
            StringComparison.Ordinal);
    }

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

            current = current.Parent;
        }

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