import {
    DedupeStrategy,
    HttpMethod,
    Polling,
    pollingHelper,
} from '@activepieces/pieces-common';
import {
    AppConnectionValueForAuthProperty,
    OAuth2PropertyValue,
    TriggerStrategy,
    createTrigger,
} from '@activepieces/pieces-framework';
import { querySalesforceApi } from '../common';

import dayjs from 'dayjs';
import { salesforceAuth } from '../..';

export const newContact = createTrigger({
    auth: salesforceAuth,
    name: 'new_contact',
    displayName: 'New Contact',
    description: 'Fires when a new Contact record is created in Salesforce.',
    aiMetadata: {
        description: 'Fires once for each new Contact record created in Salesforce, emitting all fields of the created Contact. Detected by polling for records whose CreatedDate is later than the last poll. Does not fire on updates to existing Contacts.',
    },
    props: {},
    sampleData: {
        "Id": "0037Q000005x4aXUAQ",
        "AccountId": "0017Q00000qM8c9QAC",
        "Name": "Jane Doe",
        "CreatedDate": "2025-10-10T12:00:00.000Z",
    },
    type: TriggerStrategy.POLLING,
    async test(ctx) {
        return await pollingHelper.test(polling, ctx);
    },
    async onEnable(ctx) {
        await pollingHelper.onEnable(polling, ctx);
    },
    async onDisable(ctx) {
        await pollingHelper.onDisable(polling, ctx);
    },
    async run(ctx) {
        return await pollingHelper.poll(polling, ctx);
    },
});

const polling: Polling<AppConnectionValueForAuthProperty<typeof salesforceAuth>, Record<string, never>> = {
    strategy: DedupeStrategy.TIMEBASED,
    items: async ({ auth, lastFetchEpochMS }) => {
        const isoDate = dayjs(lastFetchEpochMS).toISOString();

        const query = `
            SELECT FIELDS(ALL)
            FROM Contact
            WHERE CreatedDate > ${isoDate}
            ORDER BY CreatedDate ASC
            LIMIT 200
        `;

        const response = await querySalesforceApi<{ records: { CreatedDate: string }[] }>(
            HttpMethod.GET,
            auth,
            query
        );

        const records = response.body?.['records'] || [];

        return records.map((record: { CreatedDate: string }) => ({
            epochMilliSeconds: dayjs(record.CreatedDate).valueOf(),
            data: record,
        }));
    },
};