#!/usr/bin/perl

## no critic (Modules::RequireNoMatchVarsWithUseEnglish);
## no critic (CodeLayout::ProhibitParensWithBuiltins);
## no critic (InputOutput::RequireBracedFileHandleWithPrint);

# Connect to the shared-email database and return a list of approved
# accounts that have bee moved but not yet been created. The list
# is simply one account per line with CRLF separation.

use strict;
use warnings;
use autodie;

use Carp ;
use CGI ;
use English ;

use Stanford::Schema::WebApps::SharedEmail ;
use Stanford::WebApps::SharedEmail::Config qw(%CONFIG) ;

my $VERBOSE = 1 ;

##################################################################
sub progress {
    my ($msg) = @_ ;
    if ($VERBOSE) {
	warn "progress: $msg\n" ;
    }
    return ;
}
##################################################################

# Make connection to the shared email database.
my $dbh = Stanford::Schema::WebApps::SharedEmail->connect(\%CONFIG) ;
if (!$dbh) {
    croak 'error connecting to database: ' . $ERRNO ;
} else {
    progress('successfully made connection to database') ;
}

#my $qry = 'SELECT account FROM account '.
#   'WHERE is_approved = 1 ' .
#     'AND when_moved IS NOT NULL ' .
#     'AND when_created IS NULL ' ;

# CHANGE (2022-03-20): The "when_moved" field indicates when the Workgroup
# linkage was made. But the MaIS servers are now doing the Workgroup
# Linkage themselves so the shared-email application no longer has any
# chance to update the "when_moved" field. In other words, the
# "when_moved" field will ALWAYS be NULL. That is, the "when_moved" field
# no longer has any purpose. Thus, we REMOVE the "AND when_moved IS NOT
# NULL" clause from the above query.

my $resultset = $dbh->resultset('Account')->search({
    is_approved  => { q{=},  1},
    #when_moved   => { q{!=}, undef},
    when_created => { q{=},  undef},
                                                       });
my @results = $resultset->all() ;

progress('ran SQL query') ;

# Get accounts:
my @accounts = () ;
foreach my $result (@results) {
    my $account = $result->account ;
    push(@accounts, $account) ;
    progress("found account '$account'") ;
}

# Construct page contents:
my $contents = join("\n", @accounts) ;
progress("contents is $contents") ;

# Construct the HTML response and send.
my $q = CGI->new;
print $q->header();
print $contents ;
print "\n" ;
