/**
 * Import Files Dependencies - Factory for creating importFiles dependencies
 */

import { internal } from '../_generated/api';
import type { ActionCtx } from '../_generated/server';
import { downloadFile } from './download_file';
import { getFileMetadata } from './get_file_metadata';
import type { ImportFilesDependencies } from './import_files';

/**
 * Create dependencies for the importFiles function.
 * Binds Convex context to the dependency functions.
 */
export function createImportFilesDeps(
  ctx: ActionCtx,
  organizationId: string,
): ImportFilesDependencies {
  return {
    getFileMetadata: (itemId, token, siteId, driveId) =>
      getFileMetadata(itemId, token, siteId, driveId),
    downloadFile: (itemId, token, siteId, driveId) =>
      downloadFile(itemId, token, siteId, driveId),
    findDocumentByExternalId: async (findArgs) => {
      const doc = await ctx.runQuery(
        internal.documents.internal_queries.findDocumentByExternalId,
        findArgs,
      );
      return doc ? { _id: doc._id, contentHash: doc.contentHash } : null;
    },
    storeFile: async (blob) => ctx.storage.store(blob),
    createDocument: async (createArgs) =>
      ctx.runMutation(
        internal.documents.internal_mutations.createDocument,
        createArgs,
      ),
    updateDocument: async (updateArgs) => {
      await ctx.runMutation(
        internal.documents.internal_mutations.updateDocument,
        updateArgs,
      );
    },
    getOrCreateFolderPath: async (orgId, pathSegments, createdBy, teamId) =>
      (await ctx.runMutation(
        internal.folders.internal_mutations.getOrCreateFolderPath,
        { organizationId: orgId, pathSegments, createdBy, teamId },
      )) ?? undefined,
    saveFileMetadata: async (storageId, fileName, contentType, size) => {
      await ctx.runMutation(
        internal.file_metadata.internal_mutations.saveFileMetadata,
        {
          organizationId,
          storageId,
          fileName,
          contentType,
          size,
          // Provenance is finalized by linkDocumentToFile from the document's
          // sourceProvider ('onedrive' / 'sharepoint').
          source: 'user',
        },
      );
    },
    linkDocumentToFile: async (storageId, documentId) => {
      await ctx.runMutation(
        internal.file_metadata.internal_mutations.linkDocumentToFile,
        { storageId, documentId },
      );
    },
  };
}
