use strict;
use warnings;

use Test::More 0.96;
use if $ENV{AUTHOR_TESTING}, 'Test::Warnings';
use Test::DZil;
use Path::Tiny;
use Test::Fatal;
use File::pushd 'pushd';

use Dist::Zilla::Plugin::MakeMaker::Awesome;
{
    package Dist::Zilla::Plugin::MakeMaker::Awesome;
    use Moose;
    __PACKAGE__->meta->make_mutable;
    before _build_test_files => sub {
        ::fail '_build_test_files was called';
    };
    before _build_exe_files => sub {
        ::fail '_build_exe_files was called';
    };
}

my $tzil = Builder->from_config(
    { dist_root => 'does-not-exist' },
    {
        add_files => {
            path(qw(source dist.ini)) => simple_ini(
                'GatherDir',
            ) . <<END_INI,

[MakeMaker::Awesome]
eumm_version = 6.01
WriteMakefile_arg = CCFLAGS => '-Wall'
test_file = xt/*.t
exe_file = bin/hello-world
header = my \$string = 'oh hai';
footer = my \$other_string = 'and I like ponies';
END_INI
            path(qw(source lib DZT Sample.pm)) => 'package DZT::Sample; 1',
            path(qw(source xt foo.t)) => 'warn "here is an extra test";',
            path(qw(source bin hello-world)) => "#!/usr/bin/perl\nprint \"hello!\\n\"",
        },
    },
);

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

my $content = $tzil->slurp_file('build/Makefile.PL');

is(
    index($content,
<<EXPECTED
# This Makefile.PL for DZT-Sample was generated by
# Dist::Zilla::Plugin::MakeMaker::Awesome $Dist::Zilla::Plugin::MakeMaker::Awesome::VERSION.
# Don't edit it but the dist.ini and plugins used to construct it.

use strict;
use warnings;

use ExtUtils::MakeMaker 6.01;

my \$string = 'oh hai';

my \%WriteMakefileArgs = (
EXPECTED
    ),
    0,
    'header appears right after "use" line',
);

like(
    $content,
    qr{^\s+"TESTS"\s+=>\s+\Q"xt/*.t"\E}m,
    'test_files were set',
);
like(
    $content,
    qr{^\s+"EXE_FILES"\s+=>\s+\[\n^\s+"bin/hello-world"\n^\s+\],}m,
    'exe files were set',
);

like(
    $content,
    qr/^%WriteMakefileArgs = \(\n^    %WriteMakefileArgs,\n^    CCFLAGS => '-Wall',\n^\);\n/m,
    'additional WriteMakefile argument is set',
);

like(
    $content,
    qr/^my \$other_string = 'and I like ponies';\n\z/m,
    'footer appears right before the end of the file',
);

subtest 'run the generated Makefile.PL' => sub
{
    my $wd = pushd path($tzil->tempdir)->child('build');
    is(
        exception { $tzil->plugin_named('MakeMaker::Awesome')->build },
        undef,
        'Makefile.PL can be run successfully',
    );
};

diag 'got log messages: ', explain $tzil->log_messages
    if not Test::Builder->new->is_passing;

done_testing;
