/**
 * Returns the lowercase file extension (including dot) of a filename.
 * @param {string} name - The name of the file.
 * @returns {string} The file extension, e.g., ".png"
 */
const formattedFilenameExt = (name) => {
  const parts = typeof name === 'string' ? name.split('.') : [];
  const ext = parts.length > 1 ? parts.pop() : '';
  return ext ? `.${ext.toLowerCase()}` : '';
};

/**
 * Checks whether a file meets the size and format requirements.
 * @param {{ maxSize: number, supportedFormats: string[] }} requirements
 * @param {File} file
 * @returns {boolean}
 */
const areRequirementsFulfilled = (requirements, file) => {
  return (
    file.size <= requirements.maxSize &&
    requirements.supportedFormats.includes(formattedFilenameExt(file.name))
  );
};

/**
 * Filters a list of files into accepted and rejected based on requirements.
 * @param {FileList | File[]} files - The list of files to filter.
 * @param {{ maxSize: number, supportedFormats: string[] }} requirements
 * @returns {{ accepted: File[], rejected: File[] }}
 */
export function filterFiles(files, requirements) {
  /** @type {File[]} */
  const accepted = [];

  /** @type {File[]} */
  const rejected = [];

  for (const file of Array.from(files)) {
    if (file && areRequirementsFulfilled(requirements, file)) {
      accepted.push(file);
    } else {
      rejected.push(file);
    }
  }

  return { accepted, rejected };
}
