package EPrints::KlarasConnect::Licence;

# The licence verdict the panel last returned, and what it allows.
#
# Fail closed: no verdict, a verdict older than next_check + grace, a
# revoked installation, or a plan without repository_connect all mean no
# member access. The free health report never depends on this.

use strict;
use warnings;

use EPrints::KlarasConnect::Settings;

use constant FEATURE => 'repository_connect';
use constant DEFAULT_GRACE => 3 * 86400;

# Pure: decide from a stored record and the current time.
#   stored = { verdict => {...}, instance_status => 'verified', next_check_at => epoch, grace_seconds => n }
sub state_of
{
	my( $stored, $now ) = @_;

	$now = time if !defined $now;
	return 'none' if ref $stored ne 'HASH' || ref $stored->{verdict} ne 'HASH';

	my $status = defined $stored->{instance_status} ? $stored->{instance_status} : '';
	return 'revoked' if $status eq 'revoked';

	my $next  = _int( $stored->{next_check_at} ) ? $stored->{next_check_at} + 0 : 0;
	my $grace = _int( $stored->{grace_seconds} ) ? $stored->{grace_seconds} + 0 : DEFAULT_GRACE;
	return 'stale' if !$next || $now > $next + $grace;

	return 'invalid' if !$stored->{verdict}->{valid};
	return 'pending_verification' if $status ne 'verified';

	my $features = $stored->{verdict}->{features};
	return 'not_entitled' if ref $features ne 'HASH' || !$features->{ FEATURE() };

	return 'active';
}

sub stored
{
	my( $repo ) = @_;
	return EPrints::KlarasConnect::Settings::get_json( $repo, 'licence' );
}

sub state
{
	my( $repo ) = @_;
	return 'not_activated' if !EPrints::KlarasConnect::Settings::is_activated( $repo );
	return state_of( stored( $repo ) );
}

sub member_access
{
	my( $repo ) = @_;
	return state( $repo ) eq 'active' ? 1 : 0;
}

# Whether a heartbeat is due (the panel's next_check_at has passed).
sub due
{
	my( $repo, $now ) = @_;
	$now = time if !defined $now;
	my $s = stored( $repo );
	return 1 if ref $s ne 'HASH';
	my $next = _int( $s->{next_check_at} ) ? $s->{next_check_at} + 0 : 0;
	return !$next || $now >= $next ? 1 : 0;
}

# Store the heartbeat answer. $data is the panel's "data" object.
sub remember
{
	my( $repo, $data, $now ) = @_;

	$now = time if !defined $now;
	return 0 if ref $data ne 'HASH' || ref $data->{license} ne 'HASH';

	my $next = _iso_to_epoch( $data->{next_check_at} );
	$next = $now + 86400 if !$next || $next < $now;
	$next = $now + 7 * 86400 if $next > $now + 7 * 86400;

	my $grace = _int( $data->{grace_seconds} ) ? $data->{grace_seconds} + 0 : DEFAULT_GRACE;
	$grace = 14 * 86400 if $grace > 14 * 86400;

	my $license = $data->{license};
	my %features;
	if( ref $license->{features} eq 'HASH' )
	{
		%features = map { $_ => ( $license->{features}->{$_} ? 1 : 0 ) } grep { /\A[a-z0-9_]{1,64}\z/ } keys %{ $license->{features} };
	}

	EPrints::KlarasConnect::Settings::set_json( $repo, 'licence', {
		verdict => {
			valid      => $license->{valid} ? 1 : 0,
			status     => _str( $license->{status} ),
			plan       => ref $license->{plan} eq 'HASH' ? { name => _str( $license->{plan}->{name} ), slug => _str( $license->{plan}->{slug} ) } : undef,
			tenant     => ref $license->{tenant} eq 'HASH' ? { name => _str( $license->{tenant}->{name} ), slug => _str( $license->{tenant}->{slug} ) } : undef,
			features   => \%features,
			expires_at => _str( $license->{expires_at} ),
		},
		instance_status    => _str( $data->{instance_status} ),
		next_check_at      => $next,
		grace_seconds      => $grace,
		min_plugin_version => _str( $data->{min_plugin_version} ),
		checked_at         => $now,
	} );

	return 1;
}

# "2026-11-08T10:00:00+00:00" / "...Z" -> epoch, or undef.
sub _iso_to_epoch
{
	my( $s ) = @_;
	return undef if !defined $s || ref $s;
	my( $y, $mo, $d, $h, $mi, $sec, $tz ) =
		$s =~ /\A([0-9]{4})-([0-9]{2})-([0-9]{2})T([0-9]{2}):([0-9]{2}):([0-9]{2})(?:\.[0-9]+)?(Z|[+-][0-9]{2}:?[0-9]{2})?\z/
		or return undef;
	require Time::Local;
	my $epoch = eval { Time::Local::timegm( $sec, $mi, $h, $d, $mo - 1, $y ) };
	return undef if !defined $epoch;
	if( defined $tz && $tz ne 'Z' )
	{
		my( $sign, $th, $tm ) = $tz =~ /\A([+-])([0-9]{2}):?([0-9]{2})\z/;
		my $off = $th * 3600 + $tm * 60;
		$epoch -= $sign eq '+' ? $off : -$off;
	}
	return $epoch;
}

sub _int
{
	my( $v ) = @_;
	return defined $v && !ref $v && $v =~ /\A[0-9]{1,12}\z/ ? 1 : 0;
}

sub _str
{
	my( $v ) = @_;
	return undef if !defined $v || ref $v;
	return substr( "$v", 0, 200 );
}

1;
