use strict;
use warnings;

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

my $tzil = Builder->from_config(
    { dist_root => 'does-not-exist' },
    {
        add_files => {
            path(qw(source dist.ini)) => simple_ini(
                [ 'GatherDir' => { exclude_filename => [ qw(header.pl footer.pl) ] } ],
                [ 'MakeMaker::Awesome' => {
                    header_file => 'header.pl',
                    footer_file => 'footer.pl',
                  },
                ],
            ),
            path(qw(source lib DZT Sample.pm)) => 'package DZT::Sample; 1',
            path(qw(source header.pl)) => "# some header content\n",
            path(qw(source footer.pl)) => "# some footer content\n",
        },
    },
);

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

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

unlike($content, qr/[^\S\n]\n/, 'no trailing whitespace in generated file');

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;

# some header content

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

like(
    $content,
    qr/# some footer content\n\z/m,
    'content of footer file 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;
