use strict;
use warnings FATAL => 'all';

use Test::More;
use if $ENV{AUTHOR_TESTING}, 'Test::Warnings';
use Test::DZil;
use Test::Fatal;
use Test::Deep;
use Path::Tiny;
use Moose::Util 'find_meta';
use version;
use File::pushd 'pushd';
use Dist::Zilla::App::Command::stale;

use lib 't/lib';
use NoNetworkHits;

{
    use Dist::Zilla::Plugin::EnsureNotStale;
    my $meta = find_meta('Dist::Zilla::Plugin::EnsureNotStale');
    $meta->make_mutable;
    $meta->add_around_method_modifier(_indexed_version => sub {
        my $orig = shift;
        my $self = shift;
        my ($module) = @_;

        return version->parse('200.0') if $module eq 'Indexed::But::Not::Installed';
        die 'should not be checking for ' . $module;
    });
}

my @prompts;
{
    my $meta = find_meta('Dist::Zilla::Chrome::Test');
    $meta->make_mutable;
    $meta->add_before_method_modifier(prompt_str => sub {
        my ($self, $prompt, $arg) = @_;
        push @prompts, $prompt;
    });
}

my $tzil = Builder->from_config(
    { dist_root => 't/does-not-exist' },
    {
        add_files => {
            path(qw(source dist.ini)) => simple_ini(
                [ GatherDir => ],
                [ 'EnsureNotStale' => { modules => [ 'Indexed::But::Not::Installed' ], phase => 'build' } ],
            ),
            path(qw(source lib Foo.pm)) => "package Foo;\n1;\n",
        },
    },
);

{
    my $wd = pushd $tzil->root;
    cmp_deeply(
        [ Dist::Zilla::App::Command::stale->stale_modules($tzil) ],
        [ 'Indexed::But::Not::Installed' ],
        'app finds stale modules',
    );
    Dist::Zilla::Plugin::PromptIfStale::__clear_already_checked();
}

$tzil->chrome->logger->set_debug(1);

like(
    exception { $tzil->build },
    qr/\Q[EnsureNotStale] Aborting build\E/,
    'build aborted',
);

is(scalar @prompts, 0, 'there were no prompts') or diag 'got: ', explain \@prompts;

cmp_deeply(
    $tzil->log_messages,
    superbagof("[EnsureNotStale] Aborting build\n[EnsureNotStale] To remedy, do: cpanm Indexed::But::Not::Installed"),
    'build was aborted, with remedy instructions',
) or diag 'saw log messages: ', explain $tzil->log_messages;

done_testing;
