package EPrints::KlarasConnect::Router;

# Maps (method, path) to a controller action. Transport-agnostic: the
# Apache handler and the tests build the same request hash.
#
#   request = {
#     method  => 'GET',
#     path    => '/klaras/source/v1/records/12',   # without http_root
#     query   => { q => '...' },                    # first value of each key
#     headers => { authorization => '...' },        # lower-case names
#     body    => $bytes,                            # POST only, size-capped
#     ip      => '203.0.113.9',
#   }

use strict;
use warnings;

use EPrints::KlarasConnect;
use EPrints::KlarasConnect::Response;

my $C = EPrints::KlarasConnect::CONNECT_PREFIX;
my $S = EPrints::KlarasConnect::SOURCE_PREFIX;

# [ methods, path regex, action, needs member token ]
my @ROUTES = (
	[ [qw( GET HEAD )], qr{\A\Q$C\E/?\z},                         'connect_status',  0 ],
	[ [qw( GET )],      qr{\A\Q$C\E/verification\z},              'verification',    0 ],
	[ [qw( POST )],     qr{\A\Q$C\E/tick\z},                      'tick',            0 ],

	[ [qw( GET HEAD )], qr{\A\Q$S\E/?\z},                         'source_info',     0 ],
	[ [qw( GET )],      qr{\A\Q$S\E/session\z},                   'session',         1 ],
	[ [qw( GET )],      qr{\A\Q$S\E/discover\z},                  'discover',        1 ],
	[ [qw( GET )],      qr{\A\Q$S\E/records\z},                   'records',         1 ],
	[ [qw( GET )],      qr{\A\Q$S\E/records/([1-9][0-9]{0,9})\z}, 'record',          1 ],
	[ [qw( GET HEAD )], qr{\A\Q$S\E/records/([1-9][0-9]{0,9})/files/([1-9][0-9]{0,9})\z}, 'file', 1 ],
	[ [qw( POST )],     qr{\A\Q$S\E/events\z},                    'events',          1 ],
	[ [qw( POST )],     qr{\A\Q$S\E/searches\z},                  'searches',        1 ],
);

# True when the path belongs to this plugin at all (the rewrite trigger
# claims these and leaves every other URL to EPrints).
sub claims
{
	my( $path ) = @_;
	return defined $path && $path =~ m{\A/klaras/(?:connect|source)/v1(?:/|\z)} ? 1 : 0;
}

# Returns { action => ..., params => [...], token => 0|1 } or a Response
# hash for 404/405.
sub match
{
	my( $method, $path ) = @_;

	my $path_matched = 0;
	foreach my $route ( @ROUTES )
	{
		my( $methods, $re, $action, $token ) = @$route;
		my @params = ( $path =~ $re );
		next if !@params;
		@params = () if $#+ == 0;    # matched, but the pattern has no groups
		$path_matched = 1;
		next if !grep { $_ eq $method } @$methods;
		return { action => $action, params => \@params, token => $token };
	}

	if( $path_matched )
	{
		return EPrints::KlarasConnect::Response::error( 405, 'method_not_allowed' );
	}
	return EPrints::KlarasConnect::Response::error( 404, 'not_found' );
}

1;
