# converts additional_tests.yml 'diagnosis' section to hili4.diagnosis_lab_tests
# and results summary to hilis4.result_summary_lab_test

use Path::Tiny;
use Data::Printer;
use FindBin qw($RealBin); # warn $RealBin;

use lib (
	'/home/raj/perl-lib',
	"$RealBin/../lib",
);
use Local::DB;
use LIMS::Local::Utils;

my $dbix = Local::DB->dbix({ dbname => 'hilis4' });

my $diagnoses = $dbix->select('diagnoses', [ qw(name id) ])->map; # p $diagnoses;
my $result_summaries = $dbix->select('result_summary_options', [ qw(description id) ])->map; # p $result_summaries;

my %args = (
    app_root => path($RealBin, '..')->realpath,
    filename => '_additional_tests',
    yaml_dir => '.leeds',
); # p %args;

my $yaml = LIMS::Local::Utils::get_yaml(\%args); # p $yaml; exit;
{ # diagnoses:
	my $data = $yaml->{diagnosis}; # p $data;

	while ( my($diagnosis, $t) = each %$data ) { # p $diagnosis;
		next unless $t;

		my $diagnosis_id = $diagnoses->{$diagnosis} or die "no id for $diagnosis";
		my @test_ids    = keys %$t; # p @test_ids;
		my %h = ( diagnosis_id => $diagnosis_id );

		$dbix->delete('diagnosis_lab_test', \%h);
		for my $id(@test_ids) {
			$h{lab_test_id} = $id; # p %h;
			$dbix->insert('diagnosis_lab_test', \%h);
		}
	}
}
{ # result_summaries:
	my $data = $yaml->{results_summary}; # p $data;

	while ( my($summary, $t) = each %$data ) { # p $summary;
		my $summary_id = $result_summaries->{$summary} or die "no id for $summary";
		
		my @test_ids    = keys %$t; # p @test_ids;
		my %h = ( result_summary_id => $summary_id );

		$dbix->delete('result_summary_lab_test', \%h);
		for my $id(@test_ids) {
			$h{lab_test_id} = $id; # p %h;
			$dbix->insert('result_summary_lab_test', \%h);
		}
	}
}