#!/usr/bin/env perl

use strict;
use warnings;

use Data::Printer;
use Modern::Perl;
use AnonymiseDB;

use lib '/home/raj/perl-lib';
use Local::DB; $Local::QueryLogger::NO_QUERY_LOGS = 1;

my $dbname = $ARGV[0] || die 'require temp db name';
my $src_db = $ARGV[1] || die 'require src db name';

my $dbix = Local::DB->dbix({ dbname => $dbname });
$dbix->lc_columns = 0;

# existing nhs_numbers for anonymiser:
my $existing_nhs_nos = $dbix->select('patients', ['nhs_number', 1])->map;

my $anonymiser = AnonymiseDB->new( existing_nhs_nos => $existing_nhs_nos );

# get all patients:
my $patient = $dbix->select("$dbname.patients", '*');

say "anonymising patients ......";
while ( my $vals = $patient->hash ) { # p $vals->{id};
    say $vals->{id} unless $vals->{id} % 1000;
    $anonymiser->anonymise_patient($vals);

    my $id = $vals->{id}; # warn $p_id;
    delete $vals->{id};
    $dbix->update( "$dbname.patients", $vals, { id => $id } );
}

exit if $src_db eq 'genomics'; # need to retain participant ID (unit_number)

# get all patient_case entries:
my $patient_case = $dbix->select("$dbname.patient_case", '*');

say "anonymising unit_numbers ......";
while ( my $vals = $patient_case->hash ) {
    say $vals->{id} unless $vals->{id} % 1000;
    $anonymiser->anonymise_unit_number($vals);

    my $id = $vals->{id}; # warn $p_id;
    delete $vals->{id};
    $dbix->update( "$dbname.patient_case", $vals, { id => $id } );
}
