use strict;
use warnings;

use RT::Test tests => undef;

eval { require RT::Authen::ExternalAuth; require Net::LDAP::Server::Test; 1; } or do {
    plan skip_all => 'Unable to test without Net::LDAP and Net::LDAP::Server::Test';
};


my $ldap_port = RT::Test->find_idle_port;
ok( my $server = Net::LDAP::Server::Test->new( $ldap_port, auto_schema => 1 ),
    "spawned test LDAP server on port $ldap_port" );

my $ldap = Net::LDAP->new("localhost:$ldap_port");
$ldap->bind();
my $username = "testuser";
my $base     = "dc=bestpractical,dc=com";
my $dn       = "uid=$username,$base";
my $entry    = {
    cn           => $username,
    mail         => "$username\@invalid.tld",
    uid          => $username,
    objectClass  => 'User',
    userPassword => 'password',
};
$ldap->add( $base );
$ldap->add( $dn, attr => [%$entry] );

RT->Config->Set( ExternalAuthPriority        => ['My_LDAP'] );
RT->Config->Set( ExternalInfoPriority        => ['My_LDAP'] );
RT->Config->Set( AutoCreateNonExternalUsers  => 0 );
RT->Config->Set( AutoCreate  => undef );
RT->Config->Set(
    ExternalSettings => {    # AN EXAMPLE DB SERVICE
        'My_LDAP' => {
            'type'            => 'ldap',
            'server'          => "127.0.0.1:$ldap_port",
            'base'            => $base,
            'filter'          => '(objectClass=*)',
            'd_filter'        => '()',
            'tls'             => 0,
            'net_ldap_args'   => [ version => 3 ],
            'attr_match_list' => [ 'Name', 'EmailAddress' ],
            'attr_map'        => {
                'Name'         => 'uid',
                'EmailAddress' => 'mail',
            }
        },
    }
);
RT->Config->PostLoadCheck;

my ( $baseurl, $m ) = RT::Test->started_ok();

diag "test uri login";
{
    ok( !$m->login( 'fakeuser', 'password' ), 'not logged in with fake user' );
    $m->warning_like( qr/FAILED LOGIN for fakeuser/ );
    ok( $m->login( 'testuser', 'password' ), 'logged in' );
}
diag "test user creation";
{
    my $testuser = RT::User->new($RT::SystemUser);
    my ($ok,$msg) = $testuser->Load( 'testuser' );
    ok($ok,$msg);
    is($testuser->EmailAddress,'testuser@invalid.tld');
}


diag "test form login";
{
    $m->logout;
    $m->get_ok( $baseurl, 'base url' );
    $m->submit_form(
        form_number => 1,
        fields      => { user => 'testuser', pass => 'password', },
    );
    $m->text_contains( 'Logout', 'logged in via form' );
}

is( $m->uri, $baseurl . '/SelfService/' , 'selfservice page' );

diag "test redirect after login";
{
    $m->logout;
    $m->get_ok( $baseurl . '/SelfService/Closed.html', 'closed tickets page' );
    $m->submit_form(
        form_number => 1,
        fields      => { user => 'testuser', pass => 'password', },
    );
    $m->text_contains( 'Logout', 'logged in' );
    is( $m->uri, $baseurl . '/SelfService/Closed.html' );
}

diag "test admin user create";
{
    $m->logout;
    ok( $m->login );
    $m->get_ok( $baseurl . '/Admin/Users/Modify.html?Create=1', 'user create page' );

    my $username = 'testuser2';
    $m->submit_form(
        form_name => 'UserCreate',
        fields    => { Name => $username },
    );
    $m->text_contains( 'User could not be created: Could not set user info' );
    $m->text_lacks( 'User could not be created: Name in use' );

    my $entry = {
        cn           => $username,
        mail         => "$username\@invalid.tld",
        uid          => $username,
        objectClass  => 'User',
        userPassword => 'password',
    };
    $ldap->add( $base );
    my $dn = "uid=$username,$base";
    $ldap->add( $dn, attr => [ %$entry ] );

    $m->submit_form(
        form_name => 'UserCreate',
        fields    => { Name => '', EmailAddress => "$username\@invalid.tld" },
    );
    $m->text_contains( 'User created' );
    my ( $id ) = ( $m->uri =~ /id=(\d+)/ );
    my $user = RT::User->new( RT->SystemUser );
    $user->Load( $id );
    is( $user->EmailAddress, "$username\@invalid.tld", 'email is not changed' );
    is( $user->Name, $username, 'got canonicalized Name' );
}

$ldap->unbind();

done_testing;
