using ZB.MOM.WW.Audit;
using ZB.MOM.WW.Secrets.Abstractions;
using ZB.MOM.WW.Secrets.Cli;
using ZB.MOM.WW.Secrets.Crypto;
using ZB.MOM.WW.Secrets.Sqlite;
using ZB.MOM.WW.Secrets.Tests.Fakes;

namespace ZB.MOM.WW.Secrets.Tests.Cli;

/// <summary>
/// Exercises the headless <see cref="SecretCommands"/> layer over a real migrated SQLite store,
/// the real envelope cipher, and the real resolver — asserting round-trips, exit codes, and the
/// hard invariant that list/set output never carries a plaintext value.
/// </summary>
public sealed class SecretCommandsTests : IAsyncLifetime, IDisposable
{
    private readonly string _dbPath =
        Path.Combine(Path.GetTempPath(), $"zb-secrets-cli-{Guid.NewGuid():N}.db");

    private readonly SecretsSqliteConnectionFactory _factory;
    private readonly SqliteSecretStore _store;
    private readonly FakeMasterKeyProvider _oldKek = new("kek-cli");
    private readonly AesGcmEnvelopeCipher _cipher;
    private readonly DefaultSecretResolver _resolver;

    public SecretCommandsTests()
    {
        _factory = new SecretsSqliteConnectionFactory(_dbPath);
        _store = new SqliteSecretStore(_factory);
        _cipher = new AesGcmEnvelopeCipher(_oldKek);
        // A near-zero TTL keeps the resolver from serving a stale plaintext across a rotate/remove.
        _resolver = new DefaultSecretResolver(
            _store, _cipher, NoOpAuditWriter.Instance, TimeSpan.Zero);
    }

    public async Task InitializeAsync() =>
        await new SqliteSecretsStoreMigrator(_factory).MigrateAsync(CancellationToken.None);

    public Task DisposeAsync() => Task.CompletedTask;

    public void Dispose()
    {
        if (File.Exists(_dbPath))
        {
            try { File.Delete(_dbPath); } catch (IOException) { /* best-effort temp cleanup */ }
        }
    }

    private (SecretCommands cmd, StringWriter output) NewSut()
    {
        var output = new StringWriter();
        return (new SecretCommands(_store, _cipher, _resolver, output), output);
    }

    private static CancellationToken Ct => CancellationToken.None;

    [Fact]
    public async Task RewrapAll_MigratesRowsToNewKek_ReportsCountsWithoutLeakingValues()
    {
        var (seed, _) = NewSut();
        await seed.SetAsync("sql/a", "value-a", SecretContentType.Text, null, "alice", Ct);
        await seed.SetAsync("sql/b", "value-b", SecretContentType.Text, null, "alice", Ct);

        var newKek = new FakeMasterKeyProvider("kek-new");
        var (cmd, output) = NewSut();
        int rc = await cmd.RewrapAllAsync(_oldKek, newKek, Ct);

        Assert.Equal(0, rc);
        string outStr = output.ToString();
        Assert.Contains("\"action\":\"rewrap-all\"", outStr);
        Assert.Contains("\"total\":2", outStr);
        Assert.Contains("\"rewrapped\":2", outStr);
        Assert.Contains("\"alreadyCurrent\":0", outStr);
        // The report carries counts only — never a secret value.
        Assert.DoesNotContain("value-a", outStr);
        Assert.DoesNotContain("value-b", outStr);

        // The rows now decrypt under the NEW KEK (proof the rewrap actually re-keyed them).
        var newCipher = new AesGcmEnvelopeCipher(newKek);
        Assert.Equal("value-a", newCipher.Decrypt((await _store.GetAsync(new SecretName("sql/a"), Ct))!));
    }

    [Fact]
    public async Task RewrapAll_IdenticalKek_ReturnsErrorExitCode()
    {
        var (seed, _) = NewSut();
        await seed.SetAsync("sql/a", "value-a", SecretContentType.Text, null, "alice", Ct);

        var (cmd, output) = NewSut();
        int rc = await cmd.RewrapAllAsync(_oldKek, new FakeMasterKeyProvider("kek-cli"), Ct);

        Assert.Equal(1, rc);
        Assert.Contains("\"error\"", output.ToString());
    }

    [Fact]
    public async Task Set_Then_Get_RoundTrips()
    {
        var (cmd, setOut) = NewSut();

        int setRc = await cmd.SetAsync(
            "sql/db-conn", "hunter2", SecretContentType.ConnectionString, "prod db", "alice", Ct);

        Assert.Equal(0, setRc);
        // set confirmation must NOT leak the value.
        Assert.DoesNotContain("hunter2", setOut.ToString());
        Assert.Contains("\"action\":\"set\"", setOut.ToString());
        Assert.Contains("sql/db-conn", setOut.ToString());

        // A fresh writer for get so we can assert exactly the plaintext came back.
        var getOut = new StringWriter();
        var getCmd = new SecretCommands(_store, _cipher, _resolver, getOut);
        int getRc = await getCmd.GetAsync("sql/db-conn", Ct);

        Assert.Equal(0, getRc);
        Assert.Equal("hunter2", getOut.ToString().TrimEnd('\r', '\n'));
    }

    [Fact]
    public async Task List_PrintsMetadata_NoValues()
    {
        var (cmd, _) = NewSut();
        await cmd.SetAsync("app/one", "value-one", SecretContentType.Text, null, "alice", Ct);
        await cmd.SetAsync("app/two", "value-two", SecretContentType.Json, "second", "alice", Ct);

        var listOut = new StringWriter();
        var listCmd = new SecretCommands(_store, _cipher, _resolver, listOut);
        int rc = await listCmd.ListAsync(includeDeleted: false, Ct);

        string json = listOut.ToString();
        Assert.Equal(0, rc);
        Assert.Contains("app/one", json);
        Assert.Contains("app/two", json);
        Assert.DoesNotContain("value-one", json);
        Assert.DoesNotContain("value-two", json);
    }

    [Fact]
    public async Task Rm_Tombstones()
    {
        var (cmd, _) = NewSut();
        await cmd.SetAsync("app/gone", "bye", SecretContentType.Text, null, "alice", Ct);

        var rm1Out = new StringWriter();
        int rc1 = await new SecretCommands(_store, _cipher, _resolver, rm1Out).RemoveAsync("app/gone", "alice", Ct);
        Assert.Equal(0, rc1);
        Assert.Contains("\"found\":true", rm1Out.ToString());

        // Second remove: already tombstoned → not found.
        var rm2Out = new StringWriter();
        int rc2 = await new SecretCommands(_store, _cipher, _resolver, rm2Out).RemoveAsync("app/gone", "alice", Ct);
        Assert.NotEqual(0, rc2);
        Assert.Contains("\"found\":false", rm2Out.ToString());

        // Get after removal → not-found.
        var getOut = new StringWriter();
        int getRc = await new SecretCommands(_store, _cipher, _resolver, getOut).GetAsync("app/gone", Ct);
        Assert.NotEqual(0, getRc);
        Assert.Contains("not-found", getOut.ToString());
    }

    [Fact]
    public async Task Rotate_RequiresExisting_OverwritesInPlace()
    {
        // Rotate on a missing secret → non-zero, nothing created.
        var missingOut = new StringWriter();
        int missingRc = await new SecretCommands(_store, _cipher, _resolver, missingOut)
            .RotateAsync("app/rot", "v1", SecretContentType.Text, null, "alice", Ct);
        Assert.NotEqual(0, missingRc);

        // After a set, rotate to a new value → 0, and get returns the new value.
        await new SecretCommands(_store, _cipher, _resolver, new StringWriter())
            .SetAsync("app/rot", "v1", SecretContentType.Text, null, "alice", Ct);

        var rotateOut = new StringWriter();
        int rotateRc = await new SecretCommands(_store, _cipher, _resolver, rotateOut)
            .RotateAsync("app/rot", "v2", SecretContentType.Text, null, "bob", Ct);
        Assert.Equal(0, rotateRc);
        Assert.Contains("\"action\":\"rotate\"", rotateOut.ToString());
        Assert.DoesNotContain("v2", rotateOut.ToString());

        var getOut = new StringWriter();
        await new SecretCommands(_store, _cipher, _resolver, getOut).GetAsync("app/rot", Ct);
        Assert.Equal("v2", getOut.ToString().TrimEnd('\r', '\n'));
    }

    [Fact]
    public async Task Get_MissingSecret_ReturnsNonZero()
    {
        var (cmd, output) = NewSut();
        int rc = await cmd.GetAsync("nope/missing", Ct);

        Assert.NotEqual(0, rc);
        Assert.Contains("not-found", output.ToString());
    }
}
