use strict;
use warnings;

use Test::More 0.88;
use if $ENV{AUTHOR_TESTING}, 'Test::Warnings';

use Dist::Zilla::Plugin::ModuleBuild;
use Dist::Zilla::Plugin::ModuleBuildTiny;
plan skip_all => 'requires a Build.PL-producing plugin to have created the file by munging time'
    if not Dist::Zilla::Plugin::ModuleBuild->does('Dist::Zilla::Role::FileGatherer')
    and not Dist::Zilla::Plugin::ModuleBuildTiny->does('Dist::Zilla::Role::FileGatherer');

use Test::DZil;
use Test::Fatal;
use Path::Tiny;
use Test::Deep;

{
    package MyMunger;
    use Moose;
    with 'Dist::Zilla::Role::FileMunger';
    use List::Util 'first';
    sub munge_files {
        my $self = shift;
        my $file = first { $_->name eq 'Build.PL' } @{ $self->zilla->files };
        $file->content("# Here is a preamble and it is glorious\n" . $file->content);
    }
}

my $tzil = Builder->from_config(
    { dist_root => 'does-not-exist' },
    {
        add_files => {
            path(qw(source dist.ini)) => simple_ini(
                [ GatherDir => ],
                [ '=MyMunger' ],
                [ 'ModuleBuildTiny::Fallback' ],
            ),
            path(qw(source lib Foo.pm)) => "package Foo;\n1;\n",
        },
    },
);

$tzil->chrome->logger->set_debug(1);
is(
    exception { $tzil->build },
    undef,
    'build proceeds normally',
);

my $build_pl = $tzil->slurp_file('build/Build.PL');
unlike($build_pl, qr/[^\S\n]\n/, 'no trailing whitespace in generated Build.PL');

is(
    index($build_pl, "# Here is a preamble and it is glorious\n# This Build.PL for DZT-Sample was generated by\n# Dist::Zilla::Plugin::ModuleBuildTiny::Fallback"),
    0,
    'the preamble stayed at the front of the file',
) or diag "got Build.PL content:\n", $build_pl;

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

done_testing;
