using Microsoft.Data.SqlClient;
using Shouldly;
using Xunit;

namespace ZB.MOM.WW.OtOpcUa.Configuration.Tests;

/// <summary>
///     Creates two throwaway DB users — one in <c>OtOpcUaNode</c>, one in <c>OtOpcUaAdmin</c> —
///     and verifies the grants/denies from the <c>AuthorizationGrants</c> migration.
/// </summary>
[Trait("Category", "Authorization")]
[Collection(nameof(SchemaComplianceCollection))]
public sealed class AuthorizationTests
{
    private readonly SchemaComplianceFixture _fixture;

    /// <summary>Initializes a new instance of AuthorizationTests with the schema compliance fixture.</summary>
    /// <param name="fixture">The schema compliance test fixture.</param>
    public AuthorizationTests(SchemaComplianceFixture fixture) => _fixture = fixture;

    /// <summary>Verifies that the Node role can execute GetCurrentGenerationForCluster but not PublishGeneration.</summary>
    [Fact]
    public void Node_role_can_execute_GetCurrentGenerationForCluster_but_not_PublishGeneration()
    {
        var (user, password) = CreateUserInRole(_fixture, "Node");

        try
        {
            using var conn = OpenAs(user, password);

            Should.Throw<SqlException>(() =>
            {
                using var cmd = conn.CreateCommand();
                cmd.CommandText = "EXEC dbo.sp_PublishGeneration @ClusterId='x', @DraftGenerationId=1";
                cmd.ExecuteNonQuery();
            }).Message.ShouldContain("permission", Case.Insensitive);

            // Calling a granted proc authenticates; the proc itself will RAISERROR with Unauthorized
            // because our test principal isn't bound to any node — that's expected.
            var ex = Should.Throw<SqlException>(() =>
            {
                using var cmd = conn.CreateCommand();
                cmd.CommandText = "EXEC dbo.sp_GetCurrentGenerationForCluster @NodeId='n', @ClusterId='c'";
                cmd.ExecuteNonQuery();
            });
            ex.Message.ShouldContain("Unauthorized");
        }
        finally
        {
            DropUser(_fixture, user);
        }
    }

    /// <summary>Verifies that the Node role cannot SELECT from configuration tables directly.</summary>
    [Fact]
    public void Node_role_cannot_SELECT_from_tables_directly()
    {
        // v2 dropped the ConfigGeneration table. The Node-role authorization invariant still
        // holds: Node should not directly SELECT from a config table. Probing the v2 Deployment
        // table instead.
        var (user, password) = CreateUserInRole(_fixture, "Node");

        try
        {
            using var conn = OpenAs(user, password);
            var ex = Should.Throw<SqlException>(() =>
            {
                using var cmd = conn.CreateCommand();
                cmd.CommandText = "SELECT COUNT(*) FROM dbo.Deployment";
                cmd.ExecuteScalar();
            });
            ex.Message.ShouldContain("permission", Case.Insensitive);
        }
        finally
        {
            DropUser(_fixture, user);
        }
    }

    /// <summary>Verifies that the Admin role can execute PublishGeneration.</summary>
    [Fact]
    public void Admin_role_can_execute_PublishGeneration()
    {
        var (user, password) = CreateUserInRole(_fixture, "Admin");

        try
        {
            using var conn = OpenAs(user, password);
            // Calling the proc is permitted; content-level errors (missing draft) are OK — they
            // prove the grant succeeded (we got past the permission check into the proc body).
            var ex = Should.Throw<SqlException>(() =>
            {
                using var cmd = conn.CreateCommand();
                cmd.CommandText = "EXEC dbo.sp_PublishGeneration @ClusterId='no-such-cluster', @DraftGenerationId=9999";
                cmd.ExecuteNonQuery();
            });
            ex.Message.ShouldNotContain("permission", Case.Insensitive);
        }
        finally
        {
            DropUser(_fixture, user);
        }
    }

    /// <summary>Creates a SQL login + DB user in the given role and returns its credentials.</summary>
    private static (string User, string Password) CreateUserInRole(SchemaComplianceFixture fx, string role)
    {
        var user = $"tst_{role.ToLower()}_{Guid.NewGuid():N}"[..24];
        const string password = "TestUser_2026!";
        var dbRole = role == "Node" ? "OtOpcUaNode" : "OtOpcUaAdmin";

        // Create the login in master, the user in the test DB, and add it to the role.
        using (var conn = new SqlConnection(
                   new SqlConnectionStringBuilder(fx.ConnectionString) { InitialCatalog = "master" }.ConnectionString))
        {
            conn.Open();
            using var cmd = conn.CreateCommand();
            cmd.CommandText = $"CREATE LOGIN [{user}] WITH PASSWORD = '{password}', CHECK_POLICY = OFF;";
            cmd.ExecuteNonQuery();
        }

        using (var conn = fx.OpenConnection())
        {
            using var cmd = conn.CreateCommand();
            cmd.CommandText = $@"
CREATE USER [{user}] FOR LOGIN [{user}];
ALTER ROLE {dbRole} ADD MEMBER [{user}];";
            cmd.ExecuteNonQuery();
        }

        return (user, password);
    }

    private static void DropUser(SchemaComplianceFixture fx, string user)
    {
        try
        {
            using var dbConn = fx.OpenConnection();
            using var cmd1 = dbConn.CreateCommand();
            cmd1.CommandText = $"IF DATABASE_PRINCIPAL_ID('{user}') IS NOT NULL DROP USER [{user}];";
            cmd1.ExecuteNonQuery();
        }
        catch { /* swallow — fixture disposes the DB anyway */ }

        try
        {
            using var master = new SqlConnection(
                new SqlConnectionStringBuilder(fx.ConnectionString) { InitialCatalog = "master" }.ConnectionString);
            master.Open();
            using var cmd = master.CreateCommand();
            cmd.CommandText = $"IF SUSER_ID('{user}') IS NOT NULL DROP LOGIN [{user}];";
            cmd.ExecuteNonQuery();
        }
        catch { /* ignore */ }
    }

    private SqlConnection OpenAs(string user, string password)
    {
        var cs = new SqlConnectionStringBuilder(_fixture.ConnectionString)
        {
            UserID = user,
            Password = password,
            IntegratedSecurity = false,
        }.ConnectionString;

        var conn = new SqlConnection(cs);
        conn.Open();
        return conn;
    }
}
