namespace MBN_STOCK_WEBVIEW.LegacyApplication;

public enum LegacyDomesticStockMarket
{
    Kospi,
    Kosdaq,
    NxtKospi,
    NxtKosdaq
}

public sealed record LegacyStockIdentity(
    LegacyDomesticStockMarket Market,
    string DisplayName,
    string StockCode)
{
    public bool IsNxt => Market is
        LegacyDomesticStockMarket.NxtKospi or LegacyDomesticStockMarket.NxtKosdaq;

    public string MarketText => Market switch
    {
        LegacyDomesticStockMarket.Kospi => "코스피",
        LegacyDomesticStockMarket.Kosdaq => "코스닥",
        LegacyDomesticStockMarket.NxtKospi => "코스피_NXT",
        LegacyDomesticStockMarket.NxtKosdaq => "코스닥_NXT",
        _ => string.Empty
    };
}

public sealed class LegacyStockSearchData
{
    private readonly LegacyStockIdentity[] _masterCatalog;

    public LegacyStockSearchData(
        string query,
        IEnumerable<string> displayNames,
        IEnumerable<LegacyStockIdentity> masterCatalog)
    {
        Query = query ?? throw new ArgumentNullException(nameof(query));
        ArgumentNullException.ThrowIfNull(displayNames);
        ArgumentNullException.ThrowIfNull(masterCatalog);

        DisplayNames = Array.AsReadOnly(displayNames.ToArray());
        _masterCatalog = masterCatalog.ToArray();
        MasterCatalog = Array.AsReadOnly(_masterCatalog);
    }

    public string Query { get; }

    public IReadOnlyList<string> DisplayNames { get; }

    public IReadOnlyList<LegacyStockIdentity> MasterCatalog { get; }

    /// <summary>
    /// MainForm.jongmokCode scanned all four cached master tables without breaking.
    /// Keeping the final match therefore reproduces its duplicate-name behaviour.
    /// </summary>
    public LegacyStockIdentity? ResolveLastByDisplayName(string displayName)
    {
        LegacyStockIdentity? match = null;
        foreach (var item in _masterCatalog)
        {
            if (string.Equals(item.DisplayName, displayName, StringComparison.Ordinal))
            {
                match = item;
            }
        }

        return match;
    }
}

public interface ILegacyStockLookup
{
    Task<LegacyStockSearchData> SearchAsync(
        string query,
        CancellationToken cancellationToken = default);
}
