const EveAIApiClient = require('../api_client');

module.exports = {
  display: {
    description: "Refresh an existing document in Evie's Library with new content",
    hidden: false,
    label: 'Refresh Document in Evie',
  },
  key: 'refresh_document',
  noun: 'Document',
  operation: {
    inputFields: [
      {
        key: 'file',
        label: 'The Updated File',
        type: 'file',
        helpText: "The new content to replace the existing document",
        required: true,
      },
      {
        key: 'language',
        label: 'Document Language',
        type: 'string',
        default: 'en',
        helpText: 'Two-letter-code of the language the document is written in.',
        required: true,
      },
      {
        key: 'user_context',
        label: 'User Context',
        type: 'text',
        helpText:
            'Contextual information you want to add to the Document. If you have structured information to be shared, you can better add this information to the User Metadata, which allows for json to be uploaded.',
        required: false,
        list: false,
        altersDynamicFields: false,
      },
      {
        key: 'metadata_service',
        label: 'Service',
        type: 'string',
        default: 'Zapier',
        helpText: "By default we use 'Zapier' as service name. However, if you need to change that to e.g. give an indication of the Zapier flow, you can change this value.",
        required: true,
      },
      {
        key: 'metadata_source',
        label: 'Source App',
        type: 'string',
        helpText: "The source app of the document's origin. e.g. 'Dropbox' if the document is provided through Dropbox, or 'Google Docs' if that happens to be the origin of the document.",
        required: false,
      },
      {
        key: 'metadata_unique_id',
        label: 'Unique ID',
        type: 'string',
        helpText: 'An unique identifier, provided by the source system, if that is available.',
        required: false,
      },
      {
        key: 'metadata_unique_url',
        label: 'Unique URL',
        type: 'string',
        helpText: "A unique URL that is provided by the source system, if that's available",
        required: false,
      },
      {
        key: 'additional_metadata',
        label: 'Additional Metadata',
        helpText: "Extra metadata you'd like to add to the document",
        dict: true,
        required: false,
        altersDynamicFields: false,
      },
      {
        key: 'catalog_properties',
        label: 'Catalog Properties',
        helpText:
            'Depending on the Catalog ID provided, you can add the required key-value pairs here.',
        dict: true,
        required: false,
        altersDynamicFields: false,
      },
    ],
    perform: async (z, bundle) => {
      try {
        z.console.log("Starting New Log Trace for refresh_document");
        z.console.log("===========================================");

        const client = new EveAIApiClient(z, bundle);

        // Prepare base metadata
        const baseMetadata = {
          service: bundle.inputData.metadata_service || 'Zapier',
          source: bundle.inputData.metadata_source || '',
          unique_id: bundle.inputData.metadata_unique_id || '',
          unique_url: bundle.inputData.metadata_unique_url || '',
        };

        // If there's additional metadata, merge it
        if (bundle.inputData.additional_metadata) {
          Object.assign(baseMetadata, bundle.inputData.additional_metadata);
        }

        // First, lookup the document by unique_id
        const lookupResponse = await client.make_request('POST', '/documents/lookup', {
          lookup_criteria: { unique_id: bundle.inputData.metadata_unique_id },
          metadata_type: 'user_metadata'
        });

        const documentId = lookupResponse.document_id;
        z.console.log("Found Document ID: ", documentId)

        // Get the temporary URL from Zapier's file storage
        const tempFileUrl = await z.stashFile(bundle.inputData.file);
        z.console.log('Temporary URL created:', tempFileUrl);

        // Prepare the refresh request
        const requestData = {
          temp_url: tempFileUrl,
          language: bundle.inputData.language,
          user_metadata: JSON.stringify(baseMetadata),
        };

        // Add user_context property if it exists
        if (bundle.inputData.user_context) {
          requestData.user_context = bundle.inputData.user_context;
        }

        // Add catalog properties if they exist
        if (bundle.inputData.catalog_properties) {
          requestData.catalog_properties = JSON.stringify(bundle.inputData.catalog_properties);
        }

        // Make the refresh request
        return await client.make_request(
          'POST',
          `/documents/${documentId}/refresh_through_url`,
          requestData
        );

      } catch (error) {
        z.console.error('Error details:', {
          message: error.message,
          response: error.response ? {
            status: error.response.status,
            headers: error.response.headers,
            data: error.response.data
          } : 'No response',
          request: error.request ? {
            method: error.request.method,
            url: error.request.url,
            headers: error.request.headers
          } : 'No request'
        });
        throw error;
      }
    },
  },
};