import { __, sprintf } from '@wordpress/i18n';
import type { Link } from '../api/types/links';
import { looksLikeFile, shortUrl } from '../lib/url';

type ReasonedLink = Pick< Link, 'reason' | 'kind' | 'url' | 'final_url' >;

function notFoundText( link: ReasonedLink ): string {
	if ( link.kind === 'image' ) {
		return __( 'Image not found', 'aiplaz-link-checkup' );
	}

	if ( link.kind === 'embed' ) {
		return __( 'Video was removed', 'aiplaz-link-checkup' );
	}

	return __( 'Page not found', 'aiplaz-link-checkup' );
}

function goneText( link: ReasonedLink ): string {
	if ( looksLikeFile( link.url ) ) {
		return __( 'File was removed', 'aiplaz-link-checkup' );
	}

	return __( 'Page was removed', 'aiplaz-link-checkup' );
}

export function reasonText( link: ReasonedLink ): string {
	switch ( link.reason ) {
		case 'redirect':
			return sprintf(
				/* translators: %s: the address a link leads to now */
				__( 'Now at %s', 'aiplaz-link-checkup' ),
				shortUrl( link.final_url ?? '' )
			);
		case 'not_found':
			return notFoundText( link );
		case 'gone':
			return goneText( link );
		case 'no_host':
			return __( 'This website no longer exists', 'aiplaz-link-checkup' );
		case 'trashed':
			return __( 'You deleted this page', 'aiplaz-link-checkup' );
		case 'server_error':
			return __(
				'The other site reports an error',
				'aiplaz-link-checkup'
			);
		case 'timeout':
			return __( 'The other site did not answer', 'aiplaz-link-checkup' );
		case 'ssl':
			return __(
				'The security certificate is not valid',
				'aiplaz-link-checkup'
			);
		case 'forbidden':
			return __(
				'This site blocks automatic checks',
				'aiplaz-link-checkup'
			);
		case 'login':
			return __( 'This page needs a login', 'aiplaz-link-checkup' );
		case 'rate_limited':
			return __(
				'This site asked us to slow down',
				'aiplaz-link-checkup'
			);
		case 'ok':
			return __( 'This link works', 'aiplaz-link-checkup' );
	}
}
