package EPrints::KlarasConnect::Controller;

# One sub per route action. Each takes ( $ctx, @params ) and returns a
# Response hash. $ctx = { repo, req, claims, now }.
#
# Authentication, licence and rate limits are enforced in Handler before
# any member action runs; actions only decide what the member may see.

use strict;
use warnings;

use POSIX ();
use EPrints::KlarasConnect;
use EPrints::KlarasConnect::Access;
use EPrints::KlarasConnect::Compat;
use EPrints::KlarasConnect::Identity;
use EPrints::KlarasConnect::Licence;
use EPrints::KlarasConnect::Range;
use EPrints::KlarasConnect::RateLimit;
use EPrints::KlarasConnect::Records;
use EPrints::KlarasConnect::Response;
use EPrints::KlarasConnect::Search;
use EPrints::KlarasConnect::Settings;
use EPrints::KlarasConnect::UsageLog;
use EPrints::KlarasConnect::Util qw( hmac_hex secure_equals json_decode );

use constant TICK_WINDOW => 300;
use constant DISCOVER_TTL => 3600;


# ---------------------------------------------------------------- panel

sub connect_status
{
	my( $ctx ) = @_;
	my $repo = $ctx->{repo};
	return EPrints::KlarasConnect::Response::ok( {
		plugin_version   => EPrints::KlarasConnect::version(),
		platform         => EPrints::KlarasConnect::PLATFORM,
		platform_version => EPrints::KlarasConnect::Compat::eprints_version(),
		instance_id      => EPrints::KlarasConnect::Settings::get( $repo, 'instance_id' ),
		license_state    => EPrints::KlarasConnect::Licence::state( $repo ),
	} );
}

sub verification
{
	my( $ctx ) = @_;
	my $repo = $ctx->{repo};

	if( !EPrints::KlarasConnect::RateLimit::hit( $repo, 'verify_ip', $ctx->{req}->{ip} ) )
	{
		return _rate_limited( 'verify_ip' );
	}

	my $nonce = $ctx->{req}->{query}->{nonce};
	if( !defined $nonce || $nonce !~ /\A[A-Za-z0-9]{32,64}\z/ )
	{
		return EPrints::KlarasConnect::Response::error( 422, 'validation_failed', details => { nonce => ['Nonce tidak valid.'] } );
	}

	my $secret = EPrints::KlarasConnect::Settings::get( $repo, 'verification_secret', fresh => 1 );
	if( !defined $secret || !length $secret )
	{
		return EPrints::KlarasConnect::Response::error( 404, 'not_activated' );
	}

	return EPrints::KlarasConnect::Response::ok( {
		instance_id    => EPrints::KlarasConnect::Settings::get( $repo, 'instance_id' ),
		signature      => hmac_hex( $nonce . '|' . EPrints::KlarasConnect::Identity::base_url( $repo ), $secret ),
		plugin_version => EPrints::KlarasConnect::version(),
	} );
}

sub tick
{
	my( $ctx ) = @_;
	my $repo = $ctx->{repo};

	my $secret = EPrints::KlarasConnect::Settings::get( $repo, 'verification_secret', fresh => 1 );
	return EPrints::KlarasConnect::Response::error( 404, 'not_activated' ) if !defined $secret || !length $secret;

	# Only rejected ticks count against the IP, so junk requests from a
	# shared address cannot crowd out the panel's own.
	my $reject = sub {
		return _rate_limited( 'tick_ip' ) if !EPrints::KlarasConnect::RateLimit::hit( $repo, 'tick_ip', $ctx->{req}->{ip} );
		return EPrints::KlarasConnect::Response::error( @_ );
	};

	my $body = _body_params( $ctx->{req} );
	my $issued = defined $body->{issued_at} && $body->{issued_at} =~ /\A[0-9]{1,12}\z/ ? $body->{issued_at} + 0 : 0;
	my $nonce = $body->{nonce};
	my $sig = $body->{signature};

	if( !defined $nonce || ref $nonce || $nonce !~ /\A[A-Za-z0-9]{32,64}\z/ )
	{
		return $reject->( 422, 'validation_failed', details => { nonce => ['Nonce tidak valid.'] } );
	}
	if( abs( $ctx->{now} - $issued ) > TICK_WINDOW )
	{
		return $reject->( 401, 'stale_request', message => 'Permintaan kedaluwarsa.' );
	}

	my $iid = EPrints::KlarasConnect::Settings::get( $repo, 'instance_id' );
	my $expected = hmac_hex( "tick|$iid|$issued|$nonce", $secret );
	if( !defined $sig || ref $sig || !secure_equals( lc $sig, $expected ) )
	{
		return $reject->( 401, 'invalid_signature' );
	}
	# A signed tick runs once: a copy sent again within the window is
	# refused. (The window is far shorter than the day nonces are kept.)
	if( !EPrints::KlarasConnect::RateLimit::once( $repo, 'tick_nonce', $nonce, $issued ) )
	{
		return $reject->( 401, 'replayed_request', message => 'Permintaan ini sudah diproses.' );
	}

	require EPrints::KlarasConnect::Tick;
	my $result = EPrints::KlarasConnect::Tick::run( $repo,
		refresh => ( defined $body->{refresh} && $body->{refresh} =~ /\A(?:1|true)\z/ ) ? 1 : 0,
		source  => 'panel',
	);
	return EPrints::KlarasConnect::Response::ok( $result );
}

# ---------------------------------------------------------------- source

sub source_info
{
	my( $ctx ) = @_;
	my $repo = $ctx->{repo};
	return EPrints::KlarasConnect::Response::ok( {
		source_id        => EPrints::KlarasConnect::Settings::get( $repo, 'instance_id' ),
		platform         => EPrints::KlarasConnect::PLATFORM,
		platform_version => EPrints::KlarasConnect::Compat::eprints_version(),
		adapter_version  => EPrints::KlarasConnect::version(),
		api_version      => EPrints::KlarasConnect::API_VERSION,
		name             => EPrints::KlarasConnect::Identity::display_name( $repo ),
		capabilities     => EPrints::KlarasConnect::Identity::capabilities(),
		license_state    => EPrints::KlarasConnect::Licence::member_access( $repo ) ? 'active' : 'inactive',
		record_types     => _record_types( $repo ),
	} );
}

sub session
{
	my( $ctx ) = @_;
	return EPrints::KlarasConnect::Response::ok( {
		access     => $ctx->{claims}->{lvl},
		expires_at => _iso( $ctx->{claims}->{exp} ),
	} );
}

# Per Apache child: level|cache time -> { at, data }. See discover().
use constant RENDER_TTL => 60;
my %RENDERED;

sub discover
{
	my( $ctx ) = @_;
	my $repo = $ctx->{repo};

	my $cached = EPrints::KlarasConnect::Settings::get_json( $repo, 'discover_cache' );
	my $at = EPrints::KlarasConnect::Settings::get( $repo, 'discover_cached_at' ) || 0;
	if( ref $cached ne 'HASH' || $ctx->{now} - $at > DISCOVER_TTL * 6 )
	{
		# Normally built by the indexer every hour; build now only when the
		# cache is missing or very old, so a member never waits on it twice.
		# One child builds; the others serve the stale cache, or, with none
		# at all, wait for that one.
		require EPrints::KlarasConnect::Discover;
		my $built = EPrints::KlarasConnect::Discover::build_once( $repo, ref $cached eq 'HASH' ? 0 : 10 );
		$cached = $built if ref $built eq 'HASH';
		$cached = EPrints::KlarasConnect::Settings::get_json( $repo, 'discover_cache', fresh => 1 ) if ref $cached ne 'HASH';
		$cached = {} if ref $cached ne 'HASH';
	}

	# Section items carry per-file access, which depends on the token's
	# level only. Rendered once a minute per level in each Apache child:
	# the home screen is the busiest request, and building every item is
	# most of its cost. Safe to serve a minute old: a download decides
	# access again, from the database, every time.
	my $level = $ctx->{claims}->{lvl};
	my $key = ( defined $level ? $level : '' ) . '|' . $at;
	my $hit = $RENDERED{$key};
	if( $hit && $ctx->{now} - $hit->{at} < RENDER_TTL )
	{
		return EPrints::KlarasConnect::Response::ok( $hit->{data} );
	}

	my @sections;
	foreach my $s ( @{ $cached->{sections} || [] } )
	{
		my @items;
		foreach my $id ( @{ $s->{ids} || [] } )
		{
			my $e = EPrints::KlarasConnect::Records::live_eprint( $repo, $id ) or next;
			push @items, EPrints::KlarasConnect::Records::summary( $repo, $e, level => $level );
		}
		push @sections, { key => $s->{key}, title => $s->{title}, items => \@items } if @items;
	}

	my $data = { sections => \@sections, facets => $cached->{facets} || {} };
	%RENDERED = ( $key => { at => $ctx->{now}, data => $data }, map { $_ => $RENDERED{$_} } grep { $_ ne $key && $RENDERED{$_}->{at} > $ctx->{now} - RENDER_TTL } keys %RENDERED );
	return EPrints::KlarasConnect::Response::ok( $data );
}

sub records
{
	my( $ctx ) = @_;
	my $repo = $ctx->{repo};

	my( $p, $err ) = EPrints::KlarasConnect::Search::parse_params( $ctx->{req}->{query} );
	return EPrints::KlarasConnect::Response::error( 422, 'validation_failed', details => $err ) if !$p;

	if( length $p->{q} && !EPrints::KlarasConnect::RateLimit::hit( $repo, 'search_sub', $ctx->{claims}->{sub} ) )
	{
		return _rate_limited( 'search_sub' );
	}

	my $result = EPrints::KlarasConnect::Search::run( $repo, $p );
	my $level = $ctx->{claims}->{lvl};
	my @items;
	foreach my $e ( @{ $result->{eprints} } )
	{
		# The index can lag a record that has just been retired.
		my $status = eval { $e->value( 'eprint_status' ) };
		next if !defined $status || $status ne 'archive';
		my $s = EPrints::KlarasConnect::Records::summary( $repo, $e, level => $level );

		# full_text_status can lag document changes, and some schemas lack
		# it entirely: always confirm against the documents themselves.
		next if $p->{open_only} && !${ $s->{has_open_files} };
		next if $p->{has_files} && !${ $s->{has_files} };
		push @items, $s;
	}

	if( length $p->{q} && $p->{offset} == 0 )
	{
		EPrints::KlarasConnect::UsageLog::record_server_event( $repo, $ctx->{claims}, 'search' );
	}

	return EPrints::KlarasConnect::Response::ok( {
		items       => \@items,
		total       => $result->{total},
		next_cursor => defined $result->{next_cursor} ? '' . $result->{next_cursor} : undef,
	}, meta => {
		engine => $result->{engine},
		# Without full_text_status the file filters run on this page only, so
		# the total counts records without files too.
		( ( $p->{open_only} || $p->{has_files} ) && !EPrints::KlarasConnect::Compat::has_field( EPrints::KlarasConnect::Compat::dataset( $repo, q{eprint} ), q{full_text_status} )
			? ( total_is_estimate => \1 ) : () ),
	} );
}

sub record
{
	my( $ctx, $id ) = @_;
	my $repo = $ctx->{repo};

	my $eprint = EPrints::KlarasConnect::Records::live_eprint( $repo, $id )
		or return EPrints::KlarasConnect::Response::error( 404, 'not_found' );

	EPrints::KlarasConnect::UsageLog::record_server_event( $repo, $ctx->{claims}, 'view', eprintid => $eprint->id );

	return EPrints::KlarasConnect::Response::ok( EPrints::KlarasConnect::Records::detail( $repo, $eprint, level => $ctx->{claims}->{lvl} ) );
}

sub file
{
	my( $ctx, $eprintid, $docid ) = @_;
	my $repo = $ctx->{repo};
	my $req = $ctx->{req};

	my $eprint = EPrints::KlarasConnect::Records::live_eprint( $repo, $eprintid )
		or return EPrints::KlarasConnect::Response::error( 404, 'not_found' );

	# The document must belong to this record: ids are never trusted alone.
	my( $doc ) = grep { $_->id == $docid } eval { $eprint->get_all_documents };
	return EPrints::KlarasConnect::Response::error( 404, 'not_found' ) if !defined $doc;

	# Decided again on every download, never cached.
	my $decision = EPrints::KlarasConnect::Access::for_document( $doc,
		level           => $ctx->{claims}->{lvl},
		allow_validuser => EPrints::KlarasConnect::Settings::get( $repo, 'allow_validuser' ) ? 1 : 0,
	);
	return EPrints::KlarasConnect::Response::error( 404, 'not_found' ) if !$decision->{visible};
	if( !$decision->{available} )
	{
		return EPrints::KlarasConnect::Response::error( 403, $decision->{reason},
			details => { embargo_until => $decision->{embargo_until} } );
	}

	my $main = eval { $doc->get_main };
	my $file = defined $main ? eval { $doc->stored_file( $main ) } : undef;
	return EPrints::KlarasConnect::Response::error( 404, 'not_found' ) if !defined $file;

	my $size = ( eval { $file->value( 'filesize' ) } || 0 ) + 0;
	my $etag = EPrints::KlarasConnect::Records::etag( $file );
	my $mime = eval { $file->value( 'mime_type' ) } || 'application/octet-stream';
	$mime = 'application/octet-stream' if $mime !~ m{\A[a-z0-9.+-]+/[a-z0-9.+-]+\z}i;

	my %headers = (
		'ETag'                => qq{"$etag"},
		'Accept-Ranges'       => 'bytes',
		'Content-Type'        => $mime,
		'Content-Disposition' => EPrints::KlarasConnect::Response::content_disposition( $main ),
		'Cache-Control'       => 'private, no-cache',
	);

	if( EPrints::KlarasConnect::Range::not_modified( $req->{headers}->{'if-none-match'}, $etag ) )
	{
		return EPrints::KlarasConnect::Response::empty( 304, headers => { %headers, 'Content-Type' => undef, 'Content-Disposition' => undef } );
	}

	if( !EPrints::KlarasConnect::RateLimit::hit( $repo, 'download_sub', $ctx->{claims}->{sub} ) )
	{
		return _rate_limited( 'download_sub' );
	}

	my $range;
	if( EPrints::KlarasConnect::Range::if_range_ok( $req->{headers}->{'if-range'}, $etag ) )
	{
		$range = EPrints::KlarasConnect::Range::parse( $req->{headers}->{range}, $size );
	}
	if( defined $range && !ref $range )
	{
		return EPrints::KlarasConnect::Response::error( 416, 'range_not_satisfiable', headers => { 'Content-Range' => "bytes */$size" } );
	}

	my( $status, $offset, $length ) = ( 200, 0, $size );
	if( ref $range )
	{
		( $status, $offset, $length ) = ( 206, $range->{start}, $range->{end} - $range->{start} + 1 );
		$headers{'Content-Range'} = sprintf 'bytes %d-%d/%d', $range->{start}, $range->{end}, $size;
	}
	$headers{'Content-Length'} = $length;

	# A download counts once per member, file and day, and only when the
	# member starts from the beginning (a resumed range is the same read).
	if( $offset == 0 && $req->{method} ne 'HEAD' )
	{
		EPrints::KlarasConnect::UsageLog::record_server_event( $repo, $ctx->{claims}, 'download',
			eprintid => $eprint->id, docid => $doc->id );
	}

	my $base = EPrints::KlarasConnect::Response::base_headers();
	delete $base->{'Content-Security-Policy'};
	return {
		status  => $status,
		headers => { %$base, %headers },
		stream  => $req->{method} eq 'HEAD' ? undef : { file => $file, offset => $offset, length => $length },
		body    => '',
	};
}

sub events
{
	my( $ctx ) = @_;
	my $repo = $ctx->{repo};

	if( !EPrints::KlarasConnect::RateLimit::hit( $repo, 'events_sub', $ctx->{claims}->{sub} ) )
	{
		return _rate_limited( 'events_sub' );
	}

	my $body = json_decode( $ctx->{req}->{body} );
	if( ref $body ne 'HASH' || ref $body->{events} ne 'ARRAY' )
	{
		return EPrints::KlarasConnect::Response::error( 422, 'validation_failed', details => { events => ['Kirim daftar events.'] } );
	}
	my $events = $body->{events};
	if( @$events > EPrints::KlarasConnect::UsageLog::MAX_BATCH )
	{
		return EPrints::KlarasConnect::Response::error( 422, 'validation_failed',
			details => { events => [ 'Paling banyak ' . EPrints::KlarasConnect::UsageLog::MAX_BATCH . ' events per kiriman.' ] } );
	}

	my( @rows, %rejected );
	for my $i ( 0 .. $#$events )
	{
		my $row = EPrints::KlarasConnect::UsageLog::validate_app_event( $events->[$i], $ctx->{now} );
		if( ref $row ) { push @rows, $row }
		else { $rejected{ "events.$i" } = [ "Tidak valid: $row" ] }
	}

	my $stored = EPrints::KlarasConnect::UsageLog::record_app_events( $repo, $ctx->{claims}, \@rows );
	return EPrints::KlarasConnect::Response::error( 503, 'unavailable' ) if !defined $stored;

	return EPrints::KlarasConnect::Response::ok( {
		accepted   => $stored->{accepted},
		duplicates => $stored->{duplicates},
		ignored    => $stored->{ignored} || 0,
		rejected   => scalar( keys %rejected ),
	}, ( %rejected ? ( meta => { rejected => \%rejected } ) : () ) );
}

sub searches
{
	my( $ctx ) = @_;
	my $repo = $ctx->{repo};

	if( !EPrints::KlarasConnect::RateLimit::hit( $repo, 'search_sub', $ctx->{claims}->{sub} ) )
	{
		return _rate_limited( 'search_sub' );
	}

	my $body = json_decode( $ctx->{req}->{body} );
	my $q = ref $body eq 'HASH' ? $body->{q} : undef;
	if( !defined $q || ref $q || length( $q ) > EPrints::KlarasConnect::Search::MAX_Q )
	{
		return EPrints::KlarasConnect::Response::error( 422, 'validation_failed', details => { q => ['Kata kunci tidak valid.'] } );
	}
	my $zero = ref $body eq 'HASH' && defined $body->{results} && $body->{results} =~ /\A0\z/ ? 1 : 0;

	# Accepted either way; past a day's share per member the terms are not
	# kept, so one pseudonym cannot fill the librarian's search lists.
	EPrints::KlarasConnect::UsageLog::record_search_term( $repo, $q, $zero )
		if EPrints::KlarasConnect::RateLimit::hit( $repo, 'search_terms_sub', $ctx->{claims}->{sub} );
	return EPrints::KlarasConnect::Response::empty( 204 );
}

# ---------------------------------------------------------------- helpers

sub _rate_limited
{
	my( $kind ) = @_;
	return EPrints::KlarasConnect::Response::error( 429, 'rate_limited',
		headers => { 'Retry-After' => EPrints::KlarasConnect::RateLimit::retry_after( $kind ) } );
}

# JSON or form-encoded POST body as a flat hash.
sub _body_params
{
	my( $req ) = @_;
	my $ct = $req->{headers}->{'content-type'} || '';
	if( $ct =~ m{\Aapplication/json}i )
	{
		my $d = json_decode( $req->{body} );
		return ref $d eq 'HASH' ? $d : {};
	}
	my %p;
	foreach my $pair ( split /&/, ( defined $req->{body} ? $req->{body} : '' ) )
	{
		my( $k, $v ) = split /=/, $pair, 2;
		next if !defined $k;
		for( $k, $v ) { next if !defined; tr/+/ /; s/%([0-9A-Fa-f]{2})/chr hex $1/ge }
		$p{$k} = $v if !exists $p{$k};
	}
	return \%p;
}

sub _record_types
{
	my( $repo ) = @_;
	my $types = eval { $repo->get_types( 'eprint' ) };
	$types = eval { [ $repo->get_types( 'eprint' ) ] } if ref $types ne 'ARRAY';
	return [] if ref $types ne 'ARRAY';
	my @out;
	foreach my $t ( @$types )
	{
		my $label = eval { $repo->phrase( "eprint_typename_$t" ) };
		push @out, { key => $t, label => defined $label && $label !~ /\A\[/ ? $label : $t };
	}
	return \@out;
}

sub _iso
{
	my( $t ) = @_;
	return defined $t ? POSIX::strftime( '%Y-%m-%dT%H:%M:%SZ', gmtime $t ) : undef;
}

1;
