package EPrints::KlarasConnect::Access;

# Who may open a document through the member app. Fail closed: anything
# not recognised is treated as staff only.
#
#   eprint not in the live archive         -> not visible at all (caller 404s)
#   security "public"                      -> any valid token (same as the web)
#   embargo still running, not public      -> embargoed
#   security "validuser"                   -> token level "validuser" only,
#                                             and only while the library
#                                             allows it in the settings
#   "staffonly", empty or anything else    -> staff_only
#
# This is stricter than EPrints in one place on purpose: EPrints lets any
# signed-in user read a "validuser" document during an embargo; here an
# embargo always wins over member access.

use strict;
use warnings;

use POSIX ();

# Contract values (Source API v1 FileRef.security / .reason).
use constant SECURITY_PUBLIC  => 'public';
use constant SECURITY_MEMBERS => 'members';
use constant SECURITY_CLOSED  => 'closed';

# Decide for plain values, so it can be tested without EPrints.
#
#   decide(
#     eprint_status   => 'archive',
#     security        => 'validuser',
#     date_embargo    => '2027-01-01' | '2027-01' | '2027' | undef,
#     level           => 'validuser' | 'public',
#     allow_validuser => 1,
#     today           => 'YYYY-MM-DD',   # optional, for tests
#   )
sub decide
{
	my( %p ) = @_;

	my $security = defined $p{security} ? $p{security} : '';
	my $today = defined $p{today} ? $p{today} : POSIX::strftime( '%Y-%m-%d', gmtime );

	my $embargo_until = _embargo_end( $p{date_embargo} );
	my $embargoed = defined $embargo_until && $embargo_until gt $today ? 1 : 0;

	my %out = (
		visible       => ( defined $p{eprint_status} && $p{eprint_status} eq 'archive' ) ? 1 : 0,
		available     => 0,
		security      => SECURITY_CLOSED,
		reason        => 'staff_only',
		embargo_until => $embargoed ? $embargo_until : undef,
	);

	return \%out if !$out{visible};

	if( $security eq 'public' )
	{
		@out{qw( available security reason )} = ( 1, SECURITY_PUBLIC, undef );
		$out{embargo_until} = undef;
		return \%out;
	}

	if( $security eq 'validuser' )
	{
		$out{security} = SECURITY_MEMBERS;
		if( $embargoed )
		{
			$out{reason} = 'embargoed';
		}
		elsif( defined $p{level} && $p{level} eq 'validuser' && $p{allow_validuser} )
		{
			@out{qw( available reason )} = ( 1, undef );
		}
		else
		{
			$out{reason} = 'members_only';
		}
		return \%out;
	}

	$out{reason} = $embargoed ? 'embargoed' : 'staff_only';
	return \%out;
}

# Decide for an EPrints document object.
sub for_document
{
	my( $doc, %p ) = @_;

	my $eprint = $doc->get_parent;
	return decide(
		%p,
		eprint_status => defined $eprint ? $eprint->value( 'eprint_status' ) : undef,
		security      => $doc->value( 'security' ),
		date_embargo  => $doc->value( 'date_embargo' ),
	);
}

# EPrints dates may be "YYYY", "YYYY-MM" or "YYYY-MM-DD". A partial date
# is read as the last day it covers, so an embargo never ends early.
sub _embargo_end
{
	my( $d ) = @_;
	return undef if !defined $d || !length $d;

	if( $d =~ /\A([0-9]{4})-([0-9]{2})-([0-9]{2})/ )
	{
		return "$1-$2-$3";
	}
	if( $d =~ /\A([0-9]{4})-([0-9]{2})\z/ )
	{
		my( $y, $m ) = ( $1, $2 );
		my @days = ( 31, ( _leap( $y ) ? 29 : 28 ), 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 );
		# Not a month: unreadable, so closed like any other (below).
		return '9999-12-31' if $m < 1 || $m > 12;
		return sprintf '%04d-%02d-%02d', $y, $m, $days[ $m - 1 ];
	}
	if( $d =~ /\A([0-9]{4})\z/ )
	{
		return "$1-12-31";
	}

	# Unreadable date: treat as a far-future embargo (closed).
	return '9999-12-31';
}

sub _leap
{
	my( $y ) = @_;
	return ( $y % 4 == 0 && $y % 100 != 0 ) || $y % 400 == 0;
}

1;
