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

module.exports = {
  display: {
    description: "This action uploads a new document to Evie's Library",
    hidden: false,
    label: 'Add a new document to Evie',
  },
  key: 'add_document',
  noun: 'Document',
  operation: {
    inputFields: [
      {
        key: 'catalog_id',
        label: 'Catalog ID',
        type: 'integer',
        helpText:
            "The ID of the Catalog in Evie's Library you want to add the document to.",
        required: true,
        list: false,
        altersDynamicFields: false,
      },
      {
        key: 'file',
        label: 'The File Content',
        type: 'file',
        helpText:
            "The content of the file that needs to uploaded and indexed in Evie's Library",
        required: true,
        list: false,
        altersDynamicFields: false,
      },
      {
        key: 'name',
        label: 'Document Name',
        type: 'string',
        helpText: 'The name you want to give the Document.',
        required: true,
        list: false,
        altersDynamicFields: false,
      },
      {
        key: 'language',
        label: 'Document Language',
        type: 'string',
        default: 'en',
        helpText: 'Two-letter-code of the language the document is written in.',
        required: true,
        list: false,
        altersDynamicFields: false,
      },
      {
        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: 'valid_from',
        label: 'Valid From',
        type: 'datetime',
        helpText:
            'The moment this document is valid. When no value is given, the current data will be used.',
        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 add_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);
        }

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

        // Create request data as an object
        const requestData = {
          catalog_id: bundle.inputData.catalog_id,
          language: bundle.inputData.language,
          temp_url: tempFileUrl,
          user_metadata: JSON.stringify(baseMetadata),
        };

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

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

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

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

        // Make request to API
        return await client.make_request('POST', '/documents/add_document_through_url', requestData);

      } catch (error) {
        // Enhanced error logging
        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;
      }
    }
  }
};
