/**
 * Upload and Create Document Dependencies - Factory for creating dependencies
 */

import { internal } from '../_generated/api';
import type { ActionCtx } from '../_generated/server';
import type { UploadAndCreateDocDependencies } from './upload_and_create_document';

/**
 * Create dependencies for the uploadAndCreateDocument function.
 */
export function createUploadAndCreateDocDeps(
  ctx: ActionCtx,
  organizationId: string,
): UploadAndCreateDocDependencies {
  return {
    storageStore: async (blob) => ctx.storage.store(blob),
    createDocument: async (args) => {
      const documentId = await ctx.runMutation(
        internal.documents.internal_mutations.createDocument,
        {
          organizationId: args.organizationId,
          title: args.title,
          fileId: args.fileId,
          sourceProvider: args.sourceProvider,
          metadata: args.metadata,
          createdBy: args.createdBy,
        },
      );
      return { documentId };
    },
    updateDocument: async (args) => {
      await ctx.runMutation(
        internal.documents.internal_mutations.updateDocument,
        {
          documentId: args.documentId,
          title: args.title,
          fileId: args.fileId,
          metadata: args.metadata,
        },
      );
    },
    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 },
      );
    },
  };
}
