package API::Command::GetClientRunInfo;
use strict;
use warnings;

use Data::Dumper;
use Apache2::Const qw(OK FORBIDDEN HTTP_OK HTTP_UNAUTHORIZED HTTP_NOT_FOUND);

use lib '/app/tools/common/lib';
use Common::DB::Item::PayeeType;

use lib '/app/tools/rps/lib';
use RPS::DB::Item::ArtistPayee;
use RPS::DB::Item::ArtistRoyaltyRun;
use RPS::DB::Item::Payor;

use lib '/app/tools/api/lib';
use API::DB::Item::PortalPayee;
use API::DB::Item::PortalInvite;
use API::Util;

use base 'API::Command';

sub area { return "client"; }
sub cmd  { return "info"; }

sub execute {
    my ($self) = @_;

    my $response = $self->SUPER::execute();
    return $response if ($response);

    my $userID = $self->getRouteParam(":userId");
    my $user = AppUser::DB::Item::User->Lookup( user_id => $userID, );

    my $runtype  = $self->getRouteParam(":runTypeId");
    my $clientID = $self->getRouteParam(":clientId");

    if ( defined $user ) {

        my %data = ();
        my %clientHash;
        my %payeeHash;
        my %payorHash;

        my $portalCollection = API::DB::Item::PortalPayee->GetByUserID($userID);
        while ( $portalCollection->hasNext() ) {
            my $portalPayee = $portalCollection->next();
            if (   !$clientID
                || 0 == $clientID
                || ( $clientID && $clientID == $portalPayee->client_id ) ) {
                $clientHash{ $portalPayee->client_id } = 1;

                if ( $portalPayee->payee_type == Common::DB::Item::PayeeType::kPayeeTypeArtist ) {
                    $payeeHash{ $portalPayee->client_id }{ $portalPayee->payee_id } = 1;
                }
            }

        }

        my @clients;
        foreach my $clientID ( keys %clientHash ) {

            my %clientData = ();

            my $appSingleton = Common::RSApp->new_temporary( clientID => $clientID );
            my $dbo = Common::RSApp::GetClientDB();

            my $o = Common::DB::Item::Client->Lookup( client_id => $clientID, );
            $clientData{client_id}    = 0 + $clientID;
            $clientData{client_name}  = $o->client_name;
            $clientData{display_name} = $o->display_name;
            $clientData{email}        = $o->email;

            my %royaltyRuns;

            my @artistRuns;

            # Hash of closed/committed runs with activity for any payee
            # associated with the portal payee user for the client.
            #
            my %runInfoMap;

            if ( $runtype =~ /^artist$/i ) {

                foreach my $payeeID ( keys %{ $payeeHash{$clientID} } ) {
                    my $payee = RPS::DB::Item::ArtistPayee->Lookup( artist_payee_id => $payeeID );

                    if ($payee) {
                        my $distribution = $payee->distribution;

                        # If distribution is not set to 1, then we don't want to show this payee in the portal.
                        next() unless $distribution == 1;

                        # does this payee have any activity on closed/committed runs?

                        my $payorCollection = RPS::DB::Item::Payor->GetAll();
                        while ( $payorCollection->hasNext() ) {
                            my $payor = $payorCollection->next();

                            my $sql =
                                "SELECT r.artist_royalty_run_id, r.start_time FROM artist_royalty_run r "
                              . "JOIN artist_royalty_statement rs USING(artist_royalty_run_id) "
                              . "WHERE r.payor_id = "
                              . $payor->payor_id . " "
                              . "AND ( "
                              . "r.status = "
                              . RPS::RoyaltyRun::Status::kCommitted . " OR "
                              . "r.status = "
                              . RPS::RoyaltyRun::Status::kClosed . ") "
                              . "AND rs.payee_id = "
                              . $payeeID . " "
                              . "ORDER BY 1 DESC";
                            my $sth = $dbo->DoCmd($sql);

                            if ( $sth->rows > 0 ) {

                                while ( my ( $runID, $runStart ) = $sth->fetchrow_array() ) {

                                    my $_confirm = $payee->date_confirmed;

                                    if ( $_confirm ne '0000-00-00 00:00:00' ) {  # payee must be confirmed

                                        # found run activity, so let's remember the run
                                        $runInfoMap{$runID} = 1;
                                    }

                                }

                            }

                        }    # payor loop

                    } else {
                        die("ERROR: clientID $clientID, artist_payee $payeeID not found !!!");
                    }

                }    # payee loop

                # Now get the run info into the output JSON
                foreach my $runID ( keys {%runInfoMap} ) {

                    my $run = RPS::DB::Item::ArtistRoyaltyRun->Lookup( artist_royalty_run_id => $runID );

                    if ( !exists $payorHash{ $run->payor_id } ) {
                        my $payor = RPS::DB::Item::Payor->Lookup( payor_id => $run->payor_id );
                        $payorHash{ $run->payor_id } = $payor->name;
                    }
                    my $payorName = $payorHash{ $run->payor_id };

                    my %runData = (
                        "run_id"           => 0 + $runID,
                        "run_name"         => $run->label,
                        "payor_id"         => 0 + $run->payor_id,
                        "payor_name"       => $payorName,
                        "start_time"       => $run->start_time,
                        "end_time"         => $run->end_time,
                        "ending_sale_date" => $run->ending_sale_date,
                        "status"           => 0 + $run->status,
                    );

                    push @artistRuns, \%runData;

                }

                $royaltyRuns{artist} = \@artistRuns;

                $clientData{royalty_runs} = \%royaltyRuns;
                $clientData{num_runs} = 0 + ( scalar @artistRuns );

                push @clients, \%clientData;
            }

        }    # client

        $data{clients} = \@clients;

        return $self->createResponse(
            status => HTTP_OK,
            data   => \%data
        );
    }

    return $self->createResponse(
        status => HTTP_NOT_FOUND,
        data   => { msg => "not found" }
    );
}

1;
