package LIMS::Local::TestDB;

# provide temporary SQLite DB for t/
# ref catalyst Ch8 Testing
# requires username & password passing as hashref

use strict;
use warnings;

use Directory::Scratch;
use LIMS::Schema;
use YAML qw(DumpFile);
use FindBin qw($Bin);

my ($schema, $config);

BEGIN {
    my $tmp = Directory::Scratch->new;

    my $db = $tmp->touch('database');

    my $dsn = "DBI:SQLite:$db";

    $rose = LIMS::DB->connect($dsn);

    $config = "$Bin/../conf/lims_db_local.yml";
    DumpFile( $config, { 'Model::DB' => { connect_info => [ $dsn ] } } );
}

sub rose {
    return $rose;
}

# need to set up minimal environment for app to work:
sub setup_tables {
    my $login = shift || die 'No login details passed to setup_tables()';

    schema->resultset('Hospitals')->create(
        {
            location_name => 'Airedale',
            organisation_code => 'RCF22',
        }
    );

    schema->resultset('Trials')->create(
        {
            trial_name => 'TestTrial',
        }
    );

    schema->resultset('Groups')->create(
        {
            group_name => 'TestUser',
            idle_time  => 30,
        }
    );

    schema->resultset('Users')->create(
        {
            username => $login->{username},
            password => $login->{password},
            group_id => 1,
        }
    );

    schema->resultset('Specimens')->create(
        {
            sample_code => 'PB',
            sample_type => 'peripheral blood',
        }
    );

    schema->resultset('Clinicians')->create(
        {
            national_code => 'C9999998',
            surname       => 'Unknown',
            initials      => 'NK',
        }
    );

    schema->resultset('Requests')->create(
        {
            date            => DateTime->today,
            specimen        => 'PB',
            request_number  => 1,
            patient_id      => 1,
            case_id         => 1,
            referrer_id     => 1,
        }
    );
}

END {
    unlink $config;
}

1;