import { createAction } from '@activepieces/pieces-framework';
import {
  AuthenticationType,
  HttpMethod,
  httpClient,
} from '@activepieces/pieces-common';
import { PLUNK_BASE_URL, plunkAuth } from '../auth';

type PlunkContactsPage = {
  data?: unknown[];
  cursor?: string | null;
  hasMore?: boolean;
};

// Plunk's GET /v1/contacts is cursor-paginated. We page through with the
// max page size and accumulate items until `hasMore` is false. The page-cap
// guards against an unbounded loop if the API ever returns hasMore=true
// without advancing the cursor.
const MAX_PAGES = 200;

export const getContacts = createAction({
  auth: plunkAuth,
  name: 'get_all_contacts',
  displayName: 'Get All Contacts',
  description: 'Retrieve every contact in your Plunk project.',
  audience: 'both',
  aiMetadata: {
    description:
      'Fetches the full list of contacts in the Plunk project, automatically paging through all results. Use it to enumerate or scan contacts when you do not already have a specific contact ID. Takes no input. Read-only and idempotent.',
    idempotent: true,
  },
  props: {},
  async run(context) {
    const items: unknown[] = [];
    let cursor: string | undefined;

    for (let page = 0; page < MAX_PAGES; page++) {
      const queryParams: Record<string, string> = { limit: '100' };
      if (cursor) queryParams['cursor'] = cursor;

      const response = await httpClient.sendRequest({
        method: HttpMethod.GET,
        url: `${PLUNK_BASE_URL}/contacts`,
        queryParams,
        authentication: {
          type: AuthenticationType.BEARER_TOKEN,
          token: context.auth.props.secretKey,
        },
      });

      const body = response.body as PlunkContactsPage;
      if (body.data?.length) {
        items.push(...body.data);
      }

      if (!body.hasMore || !body.cursor) {
        break;
      }
      cursor = body.cursor;
    }

    return { items };
  },
});
