import { createTrigger, TriggerStrategy } from '@activepieces/pieces-framework';
import { HttpMethod } from '@activepieces/pieces-common';
import { attioApiCall, verifyWebhookSignature } from '../common/client';
import { attioAuth } from '../auth';
import { listIdDropdown } from '../common/props';
import { ListWebhookPayload, WebhookResponse } from '../common/types';
import { isNil } from '@activepieces/pieces-framework';

const TRIGGER_KEY = 'updated-list-entry-trigger';

export const listEntryUpdatedTrigger = createTrigger({
	name: 'list_entry_updated',
	displayName: 'List Entry Updated',
	description: 'Triggers when an existing entry is updated.',
	aiMetadata: {
		description: 'Fires when an existing entry in the selected Attio list is updated (e.g. its list-specific attribute values change). Represents a change to a record\'s entry within a list; scoped to one list chosen per trigger.',
	},
	auth: attioAuth,
	props: {
		listId: listIdDropdown({
			displayName: 'List',
			required: true,
		}),
	},
	type: TriggerStrategy.WEBHOOK,
	sampleData: {},
	async onEnable(context) {
		const response = await attioApiCall<{ data: WebhookResponse }>({
			accessToken: context.auth.secret_text,
			method: HttpMethod.POST,
			resourceUri: '/webhooks',
			body: {
				data: {
					target_url: context.webhookUrl,
					subscriptions: [
						{
							event_type: 'list-entry.updated',
							filter: {
								$and: [
									{
										field: 'id.list_id',
										operator: 'equals',
										value: context.propsValue.listId,
									},
								],
							},
						},
					],
				},
			},
		});

		await context.store.put<{ webhookId: string; WebhookSecret: string }>(TRIGGER_KEY, {
			webhookId: response.data.id.webhook_id,
			WebhookSecret: response.data.secret,
		});
	},
	async onDisable(context) {
		const webhookData = await context.store.get<{ webhookId: string; WebhookSecret: string }>(
			TRIGGER_KEY,
		);
		if (!isNil(webhookData) && webhookData.webhookId) {
			await attioApiCall({
				accessToken: context.auth.secret_text,
				method: HttpMethod.DELETE,
				resourceUri: `/webhooks/${webhookData.webhookId}`,
			});
		}
	},
	async test(context) {
		const response = await attioApiCall<{ data: Array<Record<string, any>> }>({
			accessToken: context.auth.secret_text,
			method: HttpMethod.POST,
			resourceUri: `/lists/${context.propsValue.listId}/entries/query`,
			body: {
				limit: 5,
				offset: 0,
			},
		});

		return response.data;
	},
	async run(context) {
		const triggerData = await context.store.get<{ webhookId: string; WebhookSecret: string }>(
			TRIGGER_KEY,
		);

		const webhookSecret = triggerData?.WebhookSecret;
		const webhookSignatureHeader = context.payload.headers['attio-signature'];
		const rawBody = context.payload.rawBody;

		if (!verifyWebhookSignature(webhookSecret, webhookSignatureHeader, rawBody)) {
			return [];
		}

		const payload = context.payload.body as ListWebhookPayload;
		const entryId = payload.events[0].id.entry_id;

		const response = await attioApiCall<{ data: Record<string, any> }>({
			accessToken: context.auth.secret_text,
			method: HttpMethod.GET,
			resourceUri: `/lists/${context.propsValue.listId}/entries/${entryId}`,
		});
		return [response.data];
	},
});
