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

use Data::Dumper;
use Apache2::Const qw(HTTP_FORBIDDEN HTTP_OK HTTP_UNAUTHORIZED HTTP_NOT_FOUND);
use CGI::Cookie;
use POSIX (qw/strftime/);

use lib '/app/tools/common/lib';
use Common::Util;
use AppUser::DB::Item::User;

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

use base 'API::Command';

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

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

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

    # Get route parameter
    my $userID = $self->getRouteParam(":userId");
    my $sessionUserID = $self->{userID};
    if ( $userID != $sessionUserID ) {
        return $self->createResponse(
            status => HTTP_FORBIDDEN,
            data   => { msg => "denied" }
        );
    }

    # Check if the portal user exists
    my $userObj = AppUser::DB::Item::User->Lookup(
        'user_id'   => $userID,
        'user_type' => AppUser::DB::Item::User::kUserTypePortal
    );
    if ( !$userObj ) {
        return $self->createResponse(
            status => HTTP_NOT_FOUND,
            data   => { msg => "user not found" }
        );
    }

    # Get input parameters
    my $password  = $self->getInputParam("password");
    my $firstName = $self->getInputParam("firstname");
    my $lastName  = $self->getInputParam("lastname");
    if ( defined $password ) {
        my ( $st, $emsg ) = API::Util->validatePassword( $password, $userObj );
        if ( $st != 200 ) {
            return $self->createResponse(
                status => $st,
                data   => { msg => API::Util::kInvalidPassword, emsg => $emsg }
            );
        }

        # Before saving the new password, copy the old one to the password history

        my $oldPassword = $userObj->password;
        my $lastChanged = $userObj->last_changed;
        $userObj->ArchivePassword( $userID, $oldPassword, $lastChanged );

        $userObj->UpdatePassword( $userID, $password );

        my $now = strftime "%Y-%m-%d %H:%M:%S", localtime time;
        $userObj->last_changed($now);
        $userObj->must_change(0);
    }

    $userObj->first_name($firstName) if defined $firstName;
    $userObj->last_name($lastName)   if defined $lastName;
    $userObj->save();

    return $self->createResponse(
        status => HTTP_OK,
        data   => { msg => "success" }
    );
}

1;
