package EPrints::KlarasConnect::Schema;

# The plugin's own tables, created on first use with CREATE TABLE IF NOT
# EXISTS, so enabling the package never needs "epadmin update" and an
# upgrade never loses data. MySQL / MariaDB only (what EPrints installs
# use in practice); on any other database the plugin reports itself
# unsupported instead of failing.
#
# Values that may hold non-ASCII text are BLOBs of UTF-8 JSON, so the
# database's charset (utf8 or utf8mb4) never matters.

use strict;
use warnings;

use constant SCHEMA_VERSION => 1;

my @TABLES = (
	[ klaras_connect_settings => <<'SQL' ],
CREATE TABLE IF NOT EXISTS klaras_connect_settings (
  k VARCHAR(64) NOT NULL,
  v MEDIUMBLOB NULL,
  updated_at INT UNSIGNED NOT NULL,
  PRIMARY KEY (k)
) ENGINE=InnoDB
SQL
	[ klaras_connect_events => <<'SQL' ],
CREATE TABLE IF NOT EXISTS klaras_connect_events (
  id BIGINT UNSIGNED NOT NULL AUTO_INCREMENT,
  event_id VARCHAR(64) NOT NULL,
  sub CHAR(64) NOT NULL,
  lvl TINYINT UNSIGNED NOT NULL,
  event VARCHAR(16) NOT NULL,
  eprintid INT UNSIGNED NULL,
  docid INT UNSIGNED NULL,
  value INT UNSIGNED NOT NULL DEFAULT 0,
  at INT UNSIGNED NOT NULL,
  day DATE NOT NULL,
  PRIMARY KEY (id),
  UNIQUE KEY kc_event_id (event_id),
  KEY kc_day (day),
  KEY kc_eprint_day (eprintid, day)
) ENGINE=InnoDB
SQL
	[ klaras_connect_health => <<'SQL' ],
CREATE TABLE IF NOT EXISTS klaras_connect_health (
  day DATE NOT NULL,
  report MEDIUMBLOB NOT NULL,
  created_at INT UNSIGNED NOT NULL,
  PRIMARY KEY (day)
) ENGINE=InnoDB
SQL
	# What members searched for, with no trace of who: one row per day and
	# normalised term. Feeds "Sering dicari" and "Dicari tapi tidak ada".
	[ klaras_connect_searches => <<'SQL' ],
CREATE TABLE IF NOT EXISTS klaras_connect_searches (
  day DATE NOT NULL,
  term VARBINARY(191) NOT NULL,
  hits INT UNSIGNED NOT NULL,
  zero_hits INT UNSIGNED NOT NULL,
  PRIMARY KEY (day, term)
) ENGINE=InnoDB
SQL
	[ klaras_connect_ratelimit => <<'SQL' ],
CREATE TABLE IF NOT EXISTS klaras_connect_ratelimit (
  bucket CHAR(40) NOT NULL,
  window_start INT UNSIGNED NOT NULL,
  hits INT UNSIGNED NOT NULL,
  PRIMARY KEY (bucket)
) ENGINE=InnoDB
SQL
);

my %READY;    # repository id => 1, per Apache child

sub is_supported
{
	my( $repo ) = @_;
	my $db = $repo->get_database;
	return defined $db && $db->isa( 'EPrints::Database::mysql' ) ? 1 : 0;
}

sub dbh
{
	my( $repo ) = @_;
	my $db = $repo->get_database;
	return defined $db ? $db->{dbh} : undef;
}

# Creates missing tables. Returns 1 on success, 0 (and logs) otherwise.
sub ensure
{
	my( $repo ) = @_;

	my $id = $repo->get_id;
	return 1 if $READY{$id};
	return 0 if !is_supported( $repo );

	my $dbh = dbh( $repo ) or return 0;
	foreach my $t ( @TABLES )
	{
		my( $name, $sql ) = @$t;
		my $ok = eval { local $dbh->{RaiseError} = 1; local $dbh->{PrintError} = 0; $dbh->do( $sql ); 1 };
		if( !$ok )
		{
			my $err = $@ || 'unknown error';
			$err =~ s/\s+\z//;
			$repo->log( "klaras_connect: could not create table $name: $err" );
			return 0;
		}
	}

	$READY{$id} = 1;
	return 1;
}

sub table_names
{
	return map { $_->[0] } @TABLES;
}

# Drops every plugin table. Only called from the explicit "delete data"
# action on the settings screen.
sub drop_all
{
	my( $repo ) = @_;
	my $dbh = dbh( $repo ) or return 0;
	foreach my $name ( reverse table_names() )
	{
		eval { local $dbh->{RaiseError} = 1; local $dbh->{PrintError} = 0; $dbh->do( "DROP TABLE IF EXISTS $name" ); 1 }
			or do { $repo->log( "klaras_connect: could not drop $name: $@" ); return 0 };
	}
	delete $READY{ $repo->get_id };
	return 1;
}

1;
