using System.Data;
using System.Globalization;
using Microsoft.Data.SqlClient;
using ZB.MOM.WW.Secrets.Abstractions;

namespace ZB.MOM.WW.Secrets.Replicator.SqlServer;

/// <summary>
/// SQL-Server-backed <see cref="ISecretStore"/>. Holds the same envelope-encrypted
/// <see cref="StoredSecret"/> rows as the SQLite store, in a database every node of a cluster can
/// reach — so one write is visible everywhere with no replication at all.
/// </summary>
/// <remarks>
/// <para>
/// The database holds <b>ciphertext only</b>. The KEK stays per-node and out of the database, so a
/// DBA, a backup tape, or a replica cannot decrypt anything. The corollary is a hard operational
/// constraint: every node must resolve the <em>same</em> KEK, because a row whose <c>kek_id</c> does
/// not match the local provider fails closed on resolve.
/// </para>
/// <para>
/// Semantics are deliberately identical to <c>SqliteSecretStore</c> — revision bump on upsert,
/// created stamps preserved on overwrite, verbatim last-writer-wins apply, compare-and-swap rewrap.
/// A cluster can run both stores at once (nodes on local SQLite replicating against a shared hub),
/// so a divergence between the two would be a silent convergence bug.
/// </para>
/// </remarks>
/// <param name="connectionFactory">Factory for connections to the shared secret database.</param>
public sealed class SqlServerSecretStore(SecretsSqlServerConnectionFactory connectionFactory)
    : ISecretStore, ISecretReplicationHub
{
    // All columns of the secret table, in schema order, for full-row reads.
    private const string AllColumns =
        "name, description, content_type, ciphertext, nonce, tag, wrapped_dek, wrap_nonce, wrap_tag, " +
        "kek_id, revision, is_deleted, deleted_utc, created_utc, updated_utc, created_by, updated_by";

    // The safe metadata projection — deliberately excludes every ciphertext / crypto BLOB column.
    private const string MetadataColumns =
        "name, description, content_type, kek_id, revision, is_deleted, created_utc, updated_utc, created_by, updated_by";

    private string Secret => $"[{connectionFactory.SchemaName}].[{SqlServerSecretsSchema.SecretTable}]";

    /// <inheritdoc />
    public async Task<StoredSecret?> GetAsync(SecretName name, CancellationToken ct)
    {
        await using SqlConnection connection =
            await connectionFactory.OpenConnectionAsync(ct).ConfigureAwait(false);

        await using SqlCommand command = connectionFactory.CreateCommand(
            connection, $"SELECT {AllColumns} FROM {Secret} WHERE name = @name;");
        command.Parameters.AddWithValue("@name", name.Value);

        await using SqlDataReader reader = await command.ExecuteReaderAsync(ct).ConfigureAwait(false);

        return await reader.ReadAsync(ct).ConfigureAwait(false)
            ? ReadStoredSecret(reader)
            : null;
    }

    /// <inheritdoc />
    public async Task UpsertAsync(StoredSecret row, CancellationToken ct)
    {
        ArgumentNullException.ThrowIfNull(row);

        await using SqlConnection connection =
            await connectionFactory.OpenConnectionAsync(ct).ConfigureAwait(false);

        string now = DateTimeOffset.UtcNow.ToString("O");

        // MERGE establishes revision 0 / created==updated==now on insert; on match it overwrites the
        // crypto material in place, bumps the revision, refreshes updated_utc/updated_by, and clears
        // any tombstone — but deliberately preserves created_utc / created_by (the SQLite store's
        // ON CONFLICT semantics, expressed in T-SQL).
        //
        // HOLDLOCK is not optional: without it MERGE takes only an update lock on the key range and
        // two concurrent nodes upserting the same new name can both miss the match and both INSERT,
        // producing a primary-key violation instead of one insert + one update.
        await using SqlCommand command = connectionFactory.CreateCommand(connection, $"""
            MERGE {Secret} WITH (HOLDLOCK) AS target
            USING (SELECT @name AS name) AS source
                ON target.name = source.name
            WHEN MATCHED THEN UPDATE SET
                description  = @description,
                content_type = @content_type,
                ciphertext   = @ciphertext,
                nonce        = @nonce,
                tag          = @tag,
                wrapped_dek  = @wrapped_dek,
                wrap_nonce   = @wrap_nonce,
                wrap_tag     = @wrap_tag,
                kek_id       = @kek_id,
                revision     = target.revision + 1,
                updated_utc  = @now,
                updated_by   = @updated_by,
                is_deleted   = 0,
                deleted_utc  = NULL
            WHEN NOT MATCHED THEN INSERT (
                name, description, content_type, ciphertext, nonce, tag,
                wrapped_dek, wrap_nonce, wrap_tag, kek_id, revision,
                is_deleted, deleted_utc, created_utc, updated_utc, created_by, updated_by)
            VALUES (
                @name, @description, @content_type, @ciphertext, @nonce, @tag,
                @wrapped_dek, @wrap_nonce, @wrap_tag, @kek_id, 0,
                0, NULL, @now, @now, @created_by, @updated_by);
            """);
        BindCryptoColumns(command, row);
        command.Parameters.AddWithValue("@now", now);
        command.Parameters.AddWithValue("@created_by", (object?)row.CreatedBy ?? DBNull.Value);
        command.Parameters.AddWithValue("@updated_by", (object?)row.UpdatedBy ?? DBNull.Value);

        await command.ExecuteNonQueryAsync(ct).ConfigureAwait(false);
    }

    /// <inheritdoc />
    public async Task<bool> DeleteAsync(SecretName name, string? actor, CancellationToken ct)
    {
        await using SqlConnection connection =
            await connectionFactory.OpenConnectionAsync(ct).ConfigureAwait(false);

        string now = DateTimeOffset.UtcNow.ToString("O");

        await using SqlCommand command = connectionFactory.CreateCommand(connection, $"""
            UPDATE {Secret} SET
                is_deleted  = 1,
                deleted_utc = @now,
                revision    = revision + 1,
                updated_utc = @now,
                updated_by  = @actor
            WHERE name = @name AND is_deleted = 0;
            """);
        command.Parameters.AddWithValue("@now", now);
        command.Parameters.AddWithValue("@actor", (object?)actor ?? DBNull.Value);
        command.Parameters.AddWithValue("@name", name.Value);

        int rowsAffected = await command.ExecuteNonQueryAsync(ct).ConfigureAwait(false);
        return rowsAffected > 0;
    }

    /// <inheritdoc />
    public async Task<IReadOnlyList<SecretMetadata>> ListAsync(bool includeDeleted, CancellationToken ct)
    {
        await using SqlConnection connection =
            await connectionFactory.OpenConnectionAsync(ct).ConfigureAwait(false);

        await using SqlCommand command = connectionFactory.CreateCommand(
            connection,
            $"SELECT {MetadataColumns} FROM {Secret} WHERE (@include_deleted = 1 OR is_deleted = 0) ORDER BY name;");
        command.Parameters.AddWithValue("@include_deleted", includeDeleted ? 1 : 0);

        var results = new List<SecretMetadata>();
        await using SqlDataReader reader = await command.ExecuteReaderAsync(ct).ConfigureAwait(false);
        while (await reader.ReadAsync(ct).ConfigureAwait(false))
        {
            results.Add(new SecretMetadata
            {
                Name = new SecretName(reader.GetString(0)),
                Description = reader.IsDBNull(1) ? null : reader.GetString(1),
                ContentType = Enum.Parse<SecretContentType>(reader.GetString(2)),
                KekId = reader.GetString(3),
                Revision = reader.GetInt64(4),
                IsDeleted = reader.GetBoolean(5),
                CreatedUtc = ParseUtc(reader.GetString(6)),
                UpdatedUtc = ParseUtc(reader.GetString(7)),
                CreatedBy = reader.IsDBNull(8) ? null : reader.GetString(8),
                UpdatedBy = reader.IsDBNull(9) ? null : reader.GetString(9),
            });
        }

        return results;
    }

    /// <inheritdoc />
    public async Task<IReadOnlyList<SecretManifestEntry>> GetManifestAsync(CancellationToken ct)
    {
        await using SqlConnection connection =
            await connectionFactory.OpenConnectionAsync(ct).ConfigureAwait(false);

        await using SqlCommand command = connectionFactory.CreateCommand(
            connection, $"SELECT name, revision, updated_utc, is_deleted FROM {Secret} ORDER BY name;");

        var results = new List<SecretManifestEntry>();
        await using SqlDataReader reader = await command.ExecuteReaderAsync(ct).ConfigureAwait(false);
        while (await reader.ReadAsync(ct).ConfigureAwait(false))
        {
            results.Add(new SecretManifestEntry
            {
                Name = new SecretName(reader.GetString(0)),
                Revision = reader.GetInt64(1),
                UpdatedUtc = ParseUtc(reader.GetString(2)),
                IsDeleted = reader.GetBoolean(3),
            });
        }

        return results;
    }

    /// <inheritdoc />
    public async Task ApplyReplicatedAsync(StoredSecret row, CancellationToken ct)
    {
        ArgumentNullException.ThrowIfNull(row);

        await using SqlConnection connection =
            await connectionFactory.OpenConnectionAsync(ct).ConfigureAwait(false);

        await using SqlTransaction transaction = (SqlTransaction)
            await connection.BeginTransactionAsync(IsolationLevel.Serializable, ct).ConfigureAwait(false);

        // Read the local (updated_utc, revision) so we can apply last-writer-wins. UPDLOCK/HOLDLOCK
        // keeps another node from slipping a newer row in between this read and the write below —
        // Serializable alone would not lock a key range that currently has no row.
        await using (SqlCommand read = connectionFactory.CreateCommand(
            connection,
            $"SELECT updated_utc, revision FROM {Secret} WITH (UPDLOCK, HOLDLOCK) WHERE name = @name;",
            transaction))
        {
            read.Parameters.AddWithValue("@name", row.Name.Value);

            await using SqlDataReader reader = await read.ExecuteReaderAsync(ct).ConfigureAwait(false);
            if (await reader.ReadAsync(ct).ConfigureAwait(false))
            {
                DateTimeOffset localUpdated = ParseUtc(reader.GetString(0));
                long localRevision = reader.GetInt64(1);

                // Routed through the shared predicate so every store agrees on ties.
                if (!SecretLastWriterWins.IsNewer(row.UpdatedUtc, row.Revision, localUpdated, localRevision))
                {
                    await reader.CloseAsync().ConfigureAwait(false);
                    await transaction.CommitAsync(ct).ConfigureAwait(false);
                    return;
                }
            }
        }

        // Apply the incoming row VERBATIM — its own revision, timestamps, tombstone flag, and crypto
        // material — with no revision bump (this is the replication path, not a local write).
        await using (SqlCommand upsert = connectionFactory.CreateCommand(connection, $"""
            MERGE {Secret} WITH (HOLDLOCK) AS target
            USING (SELECT @name AS name) AS source
                ON target.name = source.name
            WHEN MATCHED THEN UPDATE SET
                description  = @description,
                content_type = @content_type,
                ciphertext   = @ciphertext,
                nonce        = @nonce,
                tag          = @tag,
                wrapped_dek  = @wrapped_dek,
                wrap_nonce   = @wrap_nonce,
                wrap_tag     = @wrap_tag,
                kek_id       = @kek_id,
                revision     = @revision,
                is_deleted   = @is_deleted,
                deleted_utc  = @deleted_utc,
                created_utc  = @created_utc,
                updated_utc  = @updated_utc,
                created_by   = @created_by,
                updated_by   = @updated_by
            WHEN NOT MATCHED THEN INSERT (
                name, description, content_type, ciphertext, nonce, tag,
                wrapped_dek, wrap_nonce, wrap_tag, kek_id, revision,
                is_deleted, deleted_utc, created_utc, updated_utc, created_by, updated_by)
            VALUES (
                @name, @description, @content_type, @ciphertext, @nonce, @tag,
                @wrapped_dek, @wrap_nonce, @wrap_tag, @kek_id, @revision,
                @is_deleted, @deleted_utc, @created_utc, @updated_utc, @created_by, @updated_by);
            """, transaction))
        {
            BindCryptoColumns(upsert, row);
            upsert.Parameters.AddWithValue("@revision", row.Revision);
            upsert.Parameters.AddWithValue("@is_deleted", row.IsDeleted ? 1 : 0);
            upsert.Parameters.AddWithValue("@deleted_utc", (object?)row.DeletedUtc?.ToString("O") ?? DBNull.Value);
            upsert.Parameters.AddWithValue("@created_utc", row.CreatedUtc.ToString("O"));
            upsert.Parameters.AddWithValue("@updated_utc", row.UpdatedUtc.ToString("O"));
            upsert.Parameters.AddWithValue("@created_by", (object?)row.CreatedBy ?? DBNull.Value);
            upsert.Parameters.AddWithValue("@updated_by", (object?)row.UpdatedBy ?? DBNull.Value);

            await upsert.ExecuteNonQueryAsync(ct).ConfigureAwait(false);
        }

        await transaction.CommitAsync(ct).ConfigureAwait(false);
    }

    /// <inheritdoc />
    public async Task<bool> ApplyRewrapAsync(
        StoredSecret rewrappedRow, byte[] expectedCurrentWrappedDek, CancellationToken ct)
    {
        ArgumentNullException.ThrowIfNull(rewrappedRow);
        ArgumentNullException.ThrowIfNull(expectedCurrentWrappedDek);

        await using SqlConnection connection =
            await connectionFactory.OpenConnectionAsync(ct).ConfigureAwait(false);

        // Overwrite ONLY the KEK-wrap envelope + kek_id. Revision, updated_utc/by, the sealed body,
        // and the tombstone state are deliberately untouched — a re-wrap is not a logical change, so
        // it must not bump the revision or updated timestamp (see ISecretStore.ApplyRewrapAsync).
        //
        // Compare-and-swap on wrapped_dek: a concurrent set/rotate generates a fresh (random) DEK
        // wrap, so this matches 0 rows instead of pairing this stale re-wrap with a newer body —
        // which would leave the row permanently undecryptable. The caller re-processes a 0-row miss.
        await using SqlCommand command = connectionFactory.CreateCommand(connection, $"""
            UPDATE {Secret} SET
                wrapped_dek = @wrapped_dek,
                wrap_nonce  = @wrap_nonce,
                wrap_tag    = @wrap_tag,
                kek_id      = @kek_id
            WHERE name = @name AND wrapped_dek = @expected_wrapped_dek;
            """);
        command.Parameters.AddWithValue("@wrapped_dek", rewrappedRow.WrappedDek);
        command.Parameters.AddWithValue("@wrap_nonce", rewrappedRow.WrapNonce);
        command.Parameters.AddWithValue("@wrap_tag", rewrappedRow.WrapTag);
        command.Parameters.AddWithValue("@kek_id", rewrappedRow.KekId);
        command.Parameters.AddWithValue("@name", rewrappedRow.Name.Value);
        command.Parameters.AddWithValue("@expected_wrapped_dek", expectedCurrentWrappedDek);

        int rowsAffected = await command.ExecuteNonQueryAsync(ct).ConfigureAwait(false);
        return rowsAffected > 0;
    }

    /// <summary>
    /// Fetches several rows by name in one round trip — the replication fetch path. Names not
    /// present are simply absent from the result.
    /// </summary>
    /// <param name="names">The names to fetch.</param>
    /// <param name="ct">A token to cancel the operation.</param>
    /// <returns>The matching encrypted rows.</returns>
    public async Task<IReadOnlyList<StoredSecret>> GetManyAsync(
        IReadOnlyList<SecretName> names, CancellationToken ct)
    {
        ArgumentNullException.ThrowIfNull(names);

        if (names.Count == 0)
        {
            return [];
        }

        await using SqlConnection connection =
            await connectionFactory.OpenConnectionAsync(ct).ConfigureAwait(false);

        // One parameter per name — still fully parameterized, no name text is interpolated.
        string[] placeholders = [.. names.Select((_, i) => $"@n{i.ToString(CultureInfo.InvariantCulture)}")];

        await using SqlCommand command = connectionFactory.CreateCommand(
            connection,
            $"SELECT {AllColumns} FROM {Secret} WHERE name IN ({string.Join(", ", placeholders)});");

        for (int i = 0; i < names.Count; i++)
        {
            command.Parameters.AddWithValue(placeholders[i], names[i].Value);
        }

        var results = new List<StoredSecret>(names.Count);
        await using SqlDataReader reader = await command.ExecuteReaderAsync(ct).ConfigureAwait(false);
        while (await reader.ReadAsync(ct).ConfigureAwait(false))
        {
            results.Add(ReadStoredSecret(reader));
        }

        return results;
    }

    // Binds the identity, description, content-type, KEK id, and all six crypto BLOB columns
    // shared by every insert path.
    private static void BindCryptoColumns(SqlCommand command, StoredSecret row)
    {
        command.Parameters.AddWithValue("@name", row.Name.Value);
        command.Parameters.AddWithValue("@description", (object?)row.Description ?? DBNull.Value);
        command.Parameters.AddWithValue("@content_type", row.ContentType.ToString());
        command.Parameters.AddWithValue("@ciphertext", row.Ciphertext);
        command.Parameters.AddWithValue("@nonce", row.Nonce);
        command.Parameters.AddWithValue("@tag", row.Tag);
        command.Parameters.AddWithValue("@wrapped_dek", row.WrappedDek);
        command.Parameters.AddWithValue("@wrap_nonce", row.WrapNonce);
        command.Parameters.AddWithValue("@wrap_tag", row.WrapTag);
        command.Parameters.AddWithValue("@kek_id", row.KekId);
    }

    private static StoredSecret ReadStoredSecret(SqlDataReader reader) => new()
    {
        Name = new SecretName(reader.GetString(0)),
        Description = reader.IsDBNull(1) ? null : reader.GetString(1),
        ContentType = Enum.Parse<SecretContentType>(reader.GetString(2)),
        Ciphertext = reader.GetFieldValue<byte[]>(3),
        Nonce = reader.GetFieldValue<byte[]>(4),
        Tag = reader.GetFieldValue<byte[]>(5),
        WrappedDek = reader.GetFieldValue<byte[]>(6),
        WrapNonce = reader.GetFieldValue<byte[]>(7),
        WrapTag = reader.GetFieldValue<byte[]>(8),
        KekId = reader.GetString(9),
        Revision = reader.GetInt64(10),
        IsDeleted = reader.GetBoolean(11),
        DeletedUtc = reader.IsDBNull(12) ? null : ParseUtc(reader.GetString(12)),
        CreatedUtc = ParseUtc(reader.GetString(13)),
        UpdatedUtc = ParseUtc(reader.GetString(14)),
        CreatedBy = reader.IsDBNull(15) ? null : reader.GetString(15),
        UpdatedBy = reader.IsDBNull(16) ? null : reader.GetString(16),
    };

    private static DateTimeOffset ParseUtc(string value) =>
        DateTimeOffset.Parse(value, CultureInfo.InvariantCulture, DateTimeStyles.RoundtripKind);
}
