package EPrints::KlarasConnect::Discover;

# The search screen before a search: newest records, most read through the
# app, and facet counts. Built by the indexer every hour and stored as
# eprint ids only; GET /discover then serialises them for the member's
# token (file access differs per member).
#
# Counts use aggregate SQL on EPrints' own tables (eprint,
# eprint_divisions), whose layout has been the same since 3.0. Each query
# is guarded: a column a campus does not have just drops that facet.

use strict;
use warnings;

use EPrints::KlarasConnect::Compat;
use EPrints::KlarasConnect::Records;
use EPrints::KlarasConnect::Schema;
use EPrints::KlarasConnect::Settings;
use EPrints::KlarasConnect::UsageLog;

use constant SECTION_SIZE => 12;

sub build
{
	my( $repo ) = @_;

	my @sections;

	my @latest = _latest_ids( $repo, SECTION_SIZE );
	push @sections, { key => 'latest', title => 'Terbaru', ids => \@latest } if @latest;

	my @popular = map { '' . $_->{eprintid} } @{ EPrints::KlarasConnect::UsageLog::top_records( $repo, 30, SECTION_SIZE ) };
	push @sections, { key => 'popular', title => 'Paling banyak dibaca', ids => \@popular } if @popular >= 3;

	my $facets = {
		type      => _type_counts( $repo ),
		year      => _year_counts( $repo ),
		division  => _division_counts( $repo ),
	};

	my $cache = { sections => \@sections, facets => $facets };
	EPrints::KlarasConnect::Settings::set_json( $repo, 'discover_cache', $cache );
	EPrints::KlarasConnect::Settings::set( $repo, discover_cached_at => time );
	return $cache;
}

# build() for a request: one Apache child at a time. Returns the new cache,
# or undef when another child holds the lock past $wait seconds (the
# caller then serves the cache that one is writing, or the stale one).
sub build_once
{
	my( $repo, $wait ) = @_;
	my $dbh = EPrints::KlarasConnect::Schema::dbh( $repo ) or return build( $repo );
	my $name = 'klaras_connect_discover_' . $repo->get_id;
	my( $got ) = eval { $dbh->selectrow_array( 'SELECT GET_LOCK(?, ?)', undef, $name, $wait || 0 ) };
	return undef if !$got;
	my $cache = eval { build( $repo ) };
	my $err = $@;
	eval { $dbh->selectrow_array( 'SELECT RELEASE_LOCK(?)', undef, $name ) };
	die $err if !$cache && $err;
	return $cache;
}

sub _latest_ids
{
	my( $repo, $n ) = @_;
	my $ds = EPrints::KlarasConnect::Compat::dataset( $repo, 'archive' ) or return ();
	my @ids;
	my $ok = eval {
		my $list = $ds->search( custom_order => '-datestamp', limit => $n );
		@ids = map { '' . $_ } @{ $list->ids( 0, $n ) };
		1;
	};
	$repo->log( "klaras_connect: latest records failed: $@" ) if !$ok;
	return @ids;
}

sub _rows
{
	my( $repo, $sql, @bind ) = @_;
	my $dbh = EPrints::KlarasConnect::Schema::dbh( $repo ) or return [];
	my $rows = eval {
		local $dbh->{RaiseError} = 1; local $dbh->{PrintError} = 0;
		$dbh->selectall_arrayref( $sql, undef, @bind );
	};
	return $rows || [];
}

sub _has_column
{
	my( $repo, $table, $col ) = @_;
	my $db = $repo->get_database;
	return eval { $db->has_column( $table, $col ) } ? 1 : 0;
}

sub _type_counts
{
	my( $repo ) = @_;
	return [] if !_has_column( $repo, 'eprint', 'type' );
	my $rows = _rows( $repo,
		"SELECT type, COUNT(*) AS n FROM eprint WHERE eprint_status = 'archive' AND type IS NOT NULL GROUP BY type ORDER BY n DESC LIMIT 30" );
	return [ map {
		my $label = eval { $repo->phrase( 'eprint_typename_' . $_->[0] ) };
		{ key => $_->[0], label => ( defined $label && $label !~ /\A\[/ ? $label : $_->[0] ), count => $_->[1] + 0 }
	} @$rows ];
}

sub _year_counts
{
	my( $repo ) = @_;
	return [] if !_has_column( $repo, 'eprint', 'date_year' );
	my $rows = _rows( $repo,
		"SELECT date_year, COUNT(*) AS n FROM eprint WHERE eprint_status = 'archive' AND date_year IS NOT NULL GROUP BY date_year ORDER BY date_year DESC LIMIT 30" );
	return [ map { { key => '' . $_->[0], label => '' . $_->[0], count => $_->[1] + 0 } } @$rows ];
}

sub _division_counts
{
	my( $repo ) = @_;
	return [] if !_has_column( $repo, 'eprint_divisions', 'divisions' );
	my $rows = _rows( $repo,
		"SELECT d.divisions, COUNT(*) AS n FROM eprint_divisions d JOIN eprint e ON e.eprintid = d.eprintid "
		. "WHERE e.eprint_status = 'archive' GROUP BY d.divisions ORDER BY n DESC LIMIT 50" );
	return [ map {
		my $label = EPrints::KlarasConnect::Records::subject_label( $repo, $_->[0] );
		{ key => $_->[0], label => defined $label ? $label : $_->[0], count => $_->[1] + 0 }
	} @$rows ];
}

1;
