import { actualBudgetAuth } from '../..';
import { Property, createAction } from '@activepieces/pieces-framework';
import * as api from '@actual-app/api';
import { initializeAndDownloadBudget } from '../common/common';

export const importTransactions = createAction({
  auth: actualBudgetAuth,
  name: 'import_transactions',
  displayName: 'Import Transactions',
  description: 'Import Transactions',
  audience: 'both',
  aiMetadata: { description: 'Bulk-imports an array of transaction objects into a specified account in Actual Budget. Use it to add many transactions at once rather than one at a time; requires the target account ID and a JSON array of transactions (errors if not an array). Not idempotent — each call appends the transactions unless individual entries carry an Imported ID, which Actual uses to deduplicate against prior imports.', idempotent: false },
  props: {
    account_id: Property.ShortText({
      displayName: 'Account ID',
      description: 'ID of the account you want to import a transaction to',
      required: true,
    }),
    transactions: Property.Json({
        displayName: 'Transactions',
        description: 'A json array of the transaction object',
        required: true,
        defaultValue: [{"payee_name": "Kroger", "date": "2026-12-25", "amount": 1200 }]
    })    
  },

  async run({ auth, propsValue: { account_id, transactions } }) {
    if (!Array.isArray(transactions)) {
      throw new Error('Transactions must be a JSON array');
    }
    await initializeAndDownloadBudget(api, auth.props)
    const res = await api.importTransactions(account_id, transactions);
    await api.shutdown();
    return res;
  },
});
