package TestHelpers;

use A;
C::load 'test.conf';

use Test2::V0 qw/ diag /;
use Import::Into;


use parent qw/ Exporter /;
our @EXPORT    = qw/ read_data /;
our @EXPORT_OK = qw/ read_file diag_msg run_db /;



sub import {
	Mojo::Base->import::into(1, '-strict');
	Test2::V0->import::into(1);

	goto &Exporter::import;
}



sub diag_msg {
	my $res =  shift->tx->res;
	my $msg =  $res->json( '/details/0/1/0/message' ) // $res->json( '/message' )
		or return;
	diag sprintf '       error: %s', $msg;
}



sub run_db {
	require Schema;
	require Test::PostgreSQL;

	my @creds  =  ( '', '' );
	my $server =  Test::PostgreSQL->new();

	{
		local $D::schema = D::connect( Schema => $server->dsn, @creds );

		if( ref $_[-1] eq 'ARRAY' ) { # If we want to initialize DB
			my $sql =  pop @_;
			unshift @$sql, 'sql/_role.sql';
			@creds =  ( 'test', 'test' );

			for my $f ( @$sql ) {
				D::do read_file( $f );
			}
		}
	};

	my $conn =  D::db( Schema => $server->dsn, @creds );
	# Keep server until connection is alive.
	# Otherwise $server object will be destroyed when we leave this scope.
	$conn->{ _server } =  $server;

	return $conn;
}



use Mojo::Loader;
sub read_data {
	# Read section, Remove empty line in the end
	(Mojo::Loader::data_section scalar caller, @_) =~ s/\n{2,}$/\n/r;
}



use FindBin;
use Mojo::File;
sub read_file {
	return Mojo::File->new( $FindBin::Bin .'/' .shift )->slurp;
}



sub db_clear {
	D::T( 'Email'   )->delete;
	D::T( 'Phone'   )->delete;
	D::T( 'Address' )->delete;
	D::T( 'Country' )->delete;
	D::T( 'Company' )->delete;
}



1;
