import { __, sprintf } from '@wordpress/i18n';
import type { Link } from '../../shared/api/types/links';

const TEMPORARY_REDIRECT_CODES: readonly number[] = [ 302, 307 ];
const NO_ANSWER_CODE = 0;

function codeOr( answeredCode: number, expectedCode: number ): number {
	if ( answeredCode === NO_ANSWER_CODE ) {
		return expectedCode;
	}

	return answeredCode;
}

function redirectText( answeredCode: number ): string {
	if ( TEMPORARY_REDIRECT_CODES.includes( answeredCode ) ) {
		return sprintf(
			/* translators: %d: HTTP status code */
			__( '%d Moved for now', 'aiplaz-link-checkup' ),
			answeredCode
		);
	}

	return sprintf(
		/* translators: %d: HTTP status code */
		__( '%d Moved permanently', 'aiplaz-link-checkup' ),
		codeOr( answeredCode, 301 )
	);
}

export function answerText(
	link: Pick< Link, 'reason' | 'http_code' >
): string {
	const answeredCode = link.http_code ?? NO_ANSWER_CODE;

	switch ( link.reason ) {
		case 'redirect':
			return redirectText( answeredCode );
		case 'not_found':
			return sprintf(
				/* translators: %d: HTTP status code */
				__( '%d Not found', 'aiplaz-link-checkup' ),
				codeOr( answeredCode, 404 )
			);
		case 'gone':
			return sprintf(
				/* translators: %d: HTTP status code */
				__( '%d Gone', 'aiplaz-link-checkup' ),
				codeOr( answeredCode, 410 )
			);
		case 'no_host':
			return __( 'No such website', 'aiplaz-link-checkup' );
		case 'trashed':
			return __( 'Page is in the trash', 'aiplaz-link-checkup' );
		case 'server_error':
			return sprintf(
				/* translators: %d: HTTP status code */
				__( '%d Server error', 'aiplaz-link-checkup' ),
				codeOr( answeredCode, 500 )
			);
		case 'timeout':
			return __( 'No answer in time', 'aiplaz-link-checkup' );
		case 'ssl':
			return __( 'Certificate error', 'aiplaz-link-checkup' );
		case 'forbidden':
			return sprintf(
				/* translators: %d: HTTP status code */
				__( 'Refused (%d)', 'aiplaz-link-checkup' ),
				codeOr( answeredCode, 403 )
			);
		case 'login':
			return sprintf(
				/* translators: %d: HTTP status code */
				__( 'Login needed (%d)', 'aiplaz-link-checkup' ),
				codeOr( answeredCode, 401 )
			);
		case 'rate_limited':
			return sprintf(
				/* translators: %d: HTTP status code */
				__( 'Too many requests (%d)', 'aiplaz-link-checkup' ),
				codeOr( answeredCode, 429 )
			);
		case 'ok':
			return sprintf(
				/* translators: %d: HTTP status code */
				__( '%d OK', 'aiplaz-link-checkup' ),
				codeOr( answeredCode, 200 )
			);
	}
}
