import { nocodbAuth } from '../auth';
import { createAction, Property } from '@activepieces/pieces-framework';
import { makeClient, nocodbCommon } from '../common';
import { ListAPIResponse, ListAPIV3Response } from '../common/types';

export const searchRecordsAction = createAction({
  auth: nocodbAuth,
  name: 'nocodb-search-records',
  displayName: 'Search Records',
  description: 'Returns a list of records matching the where condition.',
  audience: 'both',
  aiMetadata: {
    description:
      'Lists rows from a NocoDB table within the chosen base, optionally narrowed by a Where filter expression and ordered by a Sort field list; leaving the Where condition empty returns all records up to the Limit. Use when an agent needs to find or browse records by criteria rather than by a known Record ID. Idempotent read-only query.',
    idempotent: true,
  },
  props: {
    workspaceId: nocodbCommon.workspaceId,
    baseId: nocodbCommon.baseId,
    tableId: nocodbCommon.tableId,
    columnId: nocodbCommon.columnId,
    whereCondition: Property.LongText({
      displayName: 'Where',
      required: false,
      description: `Enables you to define specific conditions for filtering records.See docs [here](https://docs.nocodb.com/0.109.7/developer-resources/rest-apis/#comparison-operators).`,
    }),
    limit: Property.Number({
      displayName: 'Limit',
      required: true,
      defaultValue: 10,
      description:
        'Enables you to set a limit on the number of records you want to retrieve.',
    }),
    sort: Property.LongText({
      displayName: 'Sort',
      required: false,
      description: `Comma separated field names without space.Example: **field1,-field2** will sort the records first by 'field1' in ascending order and then by 'field2' in descending order.`,
    }),
  },
  async run(context) {
    const { baseId, tableId, columnId, limit, whereCondition, sort } =
      context.propsValue;

    const client = makeClient(context.auth);
    const authVersion = context.auth.props.version || 3;
    const response = await client.listRecords(
      baseId,
      tableId,
      {
        fields: columnId ? columnId.join(',') : undefined,
        where: whereCondition,
        sort,
        offset: 0,
        limit,
      },
      authVersion
    );
    return authVersion === 4
      ? (response as ListAPIV3Response<Record<string, unknown>>).records
      : (response as ListAPIResponse<Record<string, unknown>>).list;
  },
});
