export type LocalFilePathResolver = (file: File) => string;

type LocalFileWithPath = File & {
  path?: string;
};

export function resolveLocalFilePath(
  file: File,
  options?: {
    getPathForFile?: LocalFilePathResolver;
  }
): string | undefined {
  const existingPath = (file as LocalFileWithPath).path?.trim();

  if (existingPath) {
    return existingPath;
  }

  if (!options?.getPathForFile) {
    return undefined;
  }

  try {
    const resolvedPath = options.getPathForFile(file).trim();

    return resolvedPath || undefined;
  } catch {
    return undefined;
  }
}

export function annotateLocalFilePath(
  file: File,
  options?: {
    getPathForFile?: LocalFilePathResolver;
  }
): File {
  const resolvedPath = resolveLocalFilePath(file, options);

  if (!resolvedPath) {
    return file;
  }

  try {
    Object.defineProperty(file, 'path', {
      configurable: true,
      value: resolvedPath
    });
  } catch {
    (file as LocalFileWithPath).path = resolvedPath;
  }

  return file;
}
