package EPrints::KlarasConnect::Response;

# Response values handed back to the Apache handler. Kept as plain hashes
# so routing and controllers can be tested without mod_perl.
#
#   { status => 200, headers => {...}, body => $bytes }
#   { status => 206, headers => {...}, stream => { file => $fileobj, offset => n, length => m } }

use strict;
use warnings;

use EPrints::KlarasConnect;
use EPrints::KlarasConnect::Util qw( json_encode );

# Human messages for each error code. The code is the contract with the
# app; the message may be reworded freely.
my %MESSAGES = (
	token_required    => 'Masuk ke Klaras Member untuk membuka repositori ini.',
	invalid_token     => 'Sesi repositori tidak berlaku. Buka lagi repositori ini dari aplikasi.',
	token_expired     => 'Sesi repositori sudah habis. Buka lagi repositori ini dari aplikasi.',
	wrong_audience    => 'Sesi ini untuk repositori lain. Buka lagi repositori ini dari aplikasi.',
	license_inactive  => 'Repositori ini belum terhubung ke Klaras Member. Hubungi perpustakaan.',
	not_found         => 'Karya atau berkas ini tidak ditemukan.',
	members_only      => 'Berkas ini khusus untuk anggota perpustakaan pemilik repositori.',
	staff_only        => 'Berkas ini hanya bisa dibuka petugas repositori.',
	embargoed         => 'Berkas ini masih dalam masa embargo.',
	rate_limited      => 'Terlalu banyak permintaan. Coba lagi sebentar lagi.',
	validation_failed => 'Permintaan tidak valid.',
	method_not_allowed => 'Metode ini tidak didukung untuk alamat ini.',
	invalid_signature => 'Tanda tangan permintaan tidak valid.',
	not_activated     => 'Instalasi ini belum diaktifkan.',
	range_not_satisfiable => 'Rentang berkas yang diminta tidak tersedia.',
	payload_too_large => 'Isi permintaan terlalu besar.',
	server_error      => 'Terjadi kesalahan di repositori. Coba lagi nanti.',
	unavailable       => 'Layanan sedang tidak tersedia. Coba lagi nanti.',
);

sub base_headers
{
	return {
		'X-Content-Type-Options' => 'nosniff',
		'Cache-Control'          => 'private, no-store',
		'Referrer-Policy'        => 'no-referrer',
		'X-Frame-Options'        => 'DENY',
		'Content-Security-Policy' => "default-src 'none'; frame-ancestors 'none'",
	};
}

sub json
{
	my( $status, $data, %opts ) = @_;

	my $headers = base_headers();
	$headers->{'Content-Type'} = 'application/json; charset=utf-8';
	if( $opts{headers} )
	{
		$headers->{$_} = $opts{headers}->{$_} for keys %{ $opts{headers} };
	}

	return {
		status  => $status,
		headers => $headers,
		body    => json_encode( {
			data => $data,
			meta => { api_version => EPrints::KlarasConnect::API_VERSION, %{ $opts{meta} || {} } },
		} ),
	};
}

sub ok
{
	my( $data, %opts ) = @_;
	return json( 200, $data, %opts );
}

sub error
{
	my( $status, $code, %opts ) = @_;

	my $headers = base_headers();
	$headers->{'Content-Type'} = 'application/json; charset=utf-8';
	if( $opts{headers} )
	{
		$headers->{$_} = $opts{headers}->{$_} for keys %{ $opts{headers} };
	}

	my $err = {
		code    => $code,
		message => defined $opts{message} ? $opts{message} : ( $MESSAGES{$code} || $MESSAGES{server_error} ),
	};
	$err->{details} = $opts{details} if $opts{details};

	return {
		status  => $status,
		headers => $headers,
		body    => json_encode( {
			error => $err,
			meta  => { api_version => EPrints::KlarasConnect::API_VERSION },
		} ),
	};
}

sub empty
{
	my( $status, %opts ) = @_;
	my $headers = base_headers();
	if( $opts{headers} )
	{
		$headers->{$_} = $opts{headers}->{$_} for keys %{ $opts{headers} };
	}
	return { status => $status, headers => $headers, body => '' };
}

sub message_for
{
	my( $code ) = @_;
	return $MESSAGES{$code};
}

# RFC 6266 / 5987 Content-Disposition. The ASCII fallback keeps only safe
# characters, so a stored filename can never inject a header.
sub content_disposition
{
	my( $filename, $type ) = @_;

	$type = 'attachment' if !defined $type;
	$filename = 'file' if !defined $filename || !length $filename;
	$filename =~ s{.*[/\\]}{};

	# EPrints hands out character strings (its DB handle decodes UTF-8), so
	# the name is always treated as characters, flagged or not.
	my $utf8 = $filename;
	utf8::upgrade( $utf8 );
	utf8::encode( $utf8 );

	( my $ascii = $filename ) =~ s/[^A-Za-z0-9._ -]/_/g;
	$ascii =~ s/\A[ .]+//;
	$ascii = 'file' if !length $ascii;
	$ascii = substr( $ascii, 0, 150 );

	my $encoded = join '', map {
		/[A-Za-z0-9!#\$&+.^_`|~-]/ ? $_ : sprintf( '%%%02X', ord $_ )
	} split //, $utf8;

	return sprintf q{%s; filename="%s"; filename*=UTF-8''%s}, $type, $ascii, $encoded;
}

1;
