using Microsoft.Data.Sqlite;

namespace ZB.MOM.WW.ScadaBridge.AuditLog.Site.Telemetry;

/// <summary>
/// Renders the primary/extended SQLite result codes of a
/// <see cref="SqliteException"/> for log messages. The exception's own message
/// carries only the primary code ("SQLite Error 10: 'disk I/O error'"), which
/// is too generic to act on — the 2026-07-20 disk-I/O incident
/// (known-issues/2026-07-20-localdb-disk-io-error-under-load.md) had to be
/// reproduced from scratch to learn the extended code (522 =
/// SQLITE_IOERR_SHORT_READ) that names the failing operation.
/// </summary>
internal static class SqliteErrorCodes
{
    /// <summary>
    /// "primary/extended" (e.g. "10/522") for a <see cref="SqliteException"/>
    /// anywhere in the exception chain; "n/a" for non-SQLite failures.
    /// </summary>
    public static string Describe(Exception ex)
    {
        for (Exception? e = ex; e is not null; e = e.InnerException)
        {
            if (e is SqliteException se)
            {
                return $"{se.SqliteErrorCode}/{se.SqliteExtendedErrorCode}";
            }
        }
        return "n/a";
    }
}
