package Dancer2::Plugin::JobScheduler::Testing::Utils;

use strict;
use warnings;

# ABSTRACT: Testing utilities for the package

# VERSION: generated by DZP::OurPkgVersion

use Exporter 'import';
our @EXPORT_OK = qw(
  init_db
  build_test_dbs
  db_2_managed_handle_config
  db_2_dancer2_plugin_database_config
);
our %EXPORT_TAGS = (
    'all' => [
        qw(
          init_db
          build_test_dbs
          db_2_managed_handle_config
          db_2_dancer2_plugin_database_config
        )
    ],
);

use Carp;
use Module::Load qw( load );

use Test2::V0;

use Test::Database::Temp;

sub init_db {
    my ( $driver, $dbh, $name ) = @_;
    my $module = "Dancer2::Plugin::JobScheduler::Testing::TheSchwartz::Database::Schemas::${driver}";
    load $module;
    my $schema = $module->new->schema;
    $dbh->begin_work();
    foreach my $row ( split qr/;\s*/msx, $schema ) {
        $dbh->do($row);
    }
    $dbh->commit;
    return;
}

sub build_test_dbs {
    my (@drivers) = @_;
    diag 'Create temp databases';
    my %test_dbs;
    foreach my $driver (@drivers) {
        my $test_db = Test::Database::Temp->new(
            driver => $driver,
            init   => sub {
                my ( $dbh, $name ) = @_;
                init_db( $driver, $dbh, $name );
            },
        );
        diag 'Test database (' . $test_db->driver . ') ' . $test_db->name . " created.\n";
        $test_dbs{$driver}->{ $test_db->name } = $test_db;
    }
    return %test_dbs;
}

sub db_2_managed_handle_config {
    my ($db) = @_;
    my $name = $db->name();
    my @info = $db->connection_info();
    my %c;
    @c{ 'dsn', 'username', 'password', 'attr' } = @info;
    return %c;
}

sub db_2_dancer2_plugin_database_config {
    my ($db) = @_;
    my %c;
    if ( $db->driver eq 'SQLite' ) {
        $c{'driver'}   = 'SQLite';
        $c{'database'} = $db->info->{'filepath'};
    }
    else {
        croak 'Unknown driver';
    }
    return %c;
}

# ##############################################################################
# BEGIN {
#     my @test_dbs = build_test_dbs();
#     diag Dumper \@test_dbs;
#
#     {
#         package Database::ManagedHandleConfigLocal;
#         use Moo;
#         has config => (
#             is => 'ro',
#             default => sub {
#                 return main::build_managed_handle_config(@test_dbs);
#             },
#         );
#
#         1;
#     }
#
#     ## no critic (Variables::RequireLocalizedPunctuationVars)
#     $ENV{DATABASE_MANAGED_HANDLE_CONFIG} = 'Database::ManagedHandleConfigLocal';
#     use Database::ManagedHandle;
# }

1;
