import { MimeTypeRegistry } from '../../services/MimeTypeRegistry';
import { FILE_TYPE_ERROR_INFO, INCONSISTENCY_EXTENSION_AND_MIME_TYPE_ERROR_INFO, } from './constants';
import { getFileMeta } from './utils';
const getAcceptMimeTypes = (acceptMeta) => acceptMeta.mimeTypes.concat(...acceptMeta.extensions
    .map((extension) => MimeTypeRegistry.getInstance().getMimeTypeByExtension(extension))
    .filter((value) => typeof value === 'string'));
const checkEmptyAccept = (acceptMeta) => !acceptMeta.extensions.length &&
    !acceptMeta.mimeTypes.length &&
    !acceptMeta.generalMimeTypes.length;
export const restrictFileType = (acceptMeta) => (file) => {
    if (!file || checkEmptyAccept(acceptMeta)) {
        return undefined;
    }
    const fileMeta = getFileMeta(file);
    const acceptMimeTypes = getAcceptMimeTypes(acceptMeta);
    if (acceptMeta.generalMimeTypes.length) {
        const isValid = acceptMeta.generalMimeTypes.some((mimeType) => mimeType.split('/')[0] === fileMeta.mimeType.split('/')[0]);
        if (!isValid) {
            return FILE_TYPE_ERROR_INFO;
        }
        return undefined;
    }
    const isInconsistencyExtensionAndMimeType = !MimeTypeRegistry.getInstance()
        .getExtensionsByMimeType(fileMeta.mimeType)
        ?.includes(fileMeta.extension);
    if (isInconsistencyExtensionAndMimeType) {
        return INCONSISTENCY_EXTENSION_AND_MIME_TYPE_ERROR_INFO;
    }
    if (!acceptMimeTypes.includes(fileMeta.mimeType)) {
        return FILE_TYPE_ERROR_INFO;
    }
    // Если в accept указаны только расширения, то нужно проверить соотносится ли расширение с разрешенным
    // Ибо mime type может подойти (например, image/jpeg может быть jpg, jpeg, jpe)
    if (acceptMeta.isOnlyExtensions &&
        !acceptMeta.extensions.includes(fileMeta.extension)) {
        return FILE_TYPE_ERROR_INFO;
    }
    return undefined;
};
