#!/usr/bin/perl

use Test::WWW::Mechanize::CGIApp;

use strict;
use warnings;


use Data::Printer;
use DateTime::Format::MySQL;
#use Test::More tests => 28; 
use Test::More 'no_plan';

=begin # tests:
=cut

BEGIN {
    require 't/test-lib.pl';

    # 1st test MySQL supports InnoDB tables:
    die 'no innodb support' unless mysql_supports_innodb();
}

my $test_username = 'admin_fname.admin_lname';
my $test_password = 'adm1n';

my $mech = get_mech();
my $dbix = get_dbix();

# login/logout tests handled by test-lib.pl
=begin
{ # test redirect_after_login (permitted destination url):
    my $permitted_url = '/search/notification/1';
    $mech->get_ok($permitted_url);

    # not logged in yet but check destination set correctly:
    $mech->form_name('login_form');
    like( $mech->field('destination'), qr{$permitted_url},
            'OK: intended destination detected');           #  print_and_exit();

    # login:
    $mech->submit_form(
        fields => {
            authen_username => $test_username,
            authen_password => $test_password,
        }
    );                                                        # print_and_exit();
    # print $mech->content; exit;
#   find urls containing request id:
    my @links = $mech->find_all_links( url_regex => qr{\w+/=/1} ); # eg screen/=/1
    # warn Dumper $_->url for @links; exit;
    $mech->links_ok( \@links, 'OK: nav links checked' );     #  print_and_exit();
}

do_logout();

{ # test redirect_after_login (disallowed destination url):
    my $disallowed_redirect = '/report/update_report/1?diagnosis_id=1'; # don't need rest of url'
    $mech->get_ok($disallowed_redirect);                      # print_and_exit();
    $mech->form_name('login_form');
    is( $mech->field('destination'), '', 'OK: disallowed destination url'); # print_and_exit();

    # login:
    $mech->submit_form(
        fields => {
            authen_username => $test_username,
            authen_password => $test_password,
        }
    );                                                        # print_and_exit();

    # check no rediect:
    $mech->has_tag_like(
        h2 => qr/Search for record\(s\)/,
        'OK: search page loaded, no redirect'
    );                                                        # print_and_exit();
}

do_logout();
=cut
{ # test new registration email link:
    # epoch value of admin last_login:
    $dbix->select('users', 'last_login', { username => 'admin' })->into(my $date); # p $date;
    my $epoch = DateTime::Format::MySQL->parse_datetime($date)->epoch / 100; # p $epoch;
    my $url = '/?uid=1&first_login='.$epoch 
        . '&authen_username='.$test_username
        . '&authen_password='.$test_password; # p $url;
    $mech->get_ok($url);                                      # print_and_exit();
    $mech->has_tag_like(
        h2 => qr/Search for record\(s\)/,
        'OK: logged in OK'
    );                                                        # print_and_exit();
}
