#!/usr/bin/env perl

use strict;
use lib qw(t);
use TestUtil;
use Test::More; # done_testing
use Test::Exception;
use Mock::MonkeyPatch;

no warnings 'once';


require Workflow::Factory;
require_ok( 'Workflow::Persister::DBI::AutoGeneratedId' );
require_ok( 'Workflow::Persister::DBI' );

my $DATE_FORMAT = '%Y-%m-%d %H:%M';

my @persisters = ({
    name  => 'MockPersister',
    class => 'Workflow::Persister::DBI',
    dsn   => 'DBI:Mock:',
    date_format => $DATE_FORMAT,
});

my $factory = Workflow::Factory->instance;

lives_ok { $factory->add_config( persister => \@persisters ) }
   'Successful persister creation' ;
TestUtil->init_factory();

my $persister = $factory->get_persister( 'MockPersister' );
my $handle = $persister->handle;

is ($persister->dsn(), 'DBI:Mock:', 'Got back DSN from config.');
is ($persister->date_format(), '%Y-%m-%d %H:%M', 'Got back date format from config.');

{
    # MySQL like, ref: Workflow::Persister::DBI
    my $generator = Workflow::Persister::DBI::AutoGeneratedId->new({ from_handle => 'database', handle_property => 'last_insert_id' });
    is( ref( $generator ), 'Workflow::Persister::DBI::AutoGeneratedId',
        'Object created of correct type' );

    is($generator->pre_fetch_id, undef, 'Calling pre_fetch_id');

    # Injecting directly, not pretty, but works
    $handle->{last_insert_id} = 1;

    is($generator->post_fetch_id($handle), 1, 'Value returned from generator' );
}

{
    # Also MySQL like, ref: Workflow::Persister::DBI
    my $generator = Workflow::Persister::DBI::AutoGeneratedId->new({ from_handle => 'statement', handle_property => 'last_insert_id' });
    is( ref( $generator ), 'Workflow::Persister::DBI::AutoGeneratedId',
        'Object created of correct type' );

    is($generator->pre_fetch_id, undef, 'Calling pre_fetch_id');

    # Injecting directly, not pretty, but works
    my $sth->{last_insert_id} = 1;

    is($generator->post_fetch_id($handle, $sth), 1, 'Value returned from generator' );
}

{
    # SQLite like, ref: Workflow::Persister::DBI
    my $generator = Workflow::Persister::DBI::AutoGeneratedId->new({ func_property => 'last_insert_id' });
    is( ref( $generator ), 'Workflow::Persister::DBI::AutoGeneratedId',
        'Object created of correct type' );

    is($generator->pre_fetch_id, undef, 'Calling pre_fetch_id');

    my $mock = Mock::MonkeyPatch->patch(
        'DBD::Mock::db::last_insert_id' => sub { 1 }
    );

    is($generator->post_fetch_id($handle), 1, 'Value returned from generator' );
}

done_testing();
