import type { ProviderDescriptor } from './types';

export const webhookDescriptor: ProviderDescriptor = {
	type: 'webhook',
	defaultName: 'Generic Webhook',
	icon: 'mdiWebhook',
	hasUrl: false,

	configFields: [
		{
			key: 'auth_mode', configKey: 'auth_mode',
			label: 'providers.authMode',
			type: 'grid-select',
			gridItems: 'webhookAuthModeItems',
			gridColumns: 3,
			defaultValue: 'none',
		},
		{
			key: 'webhook_secret', configKey: 'webhook_secret',
			label: 'providers.webhookSecret', editLabel: 'providers.webhookSecretKeep',
			type: 'password', optional: true,
			hint: 'providers.genericWebhookSecretHint',
		},
		{
			key: 'max_stored_payloads', configKey: 'max_stored_payloads',
			label: 'providers.maxStoredPayloads',
			type: 'number',
			min: 0, max: 100,
			defaultValue: 20,
			hint: 'providers.maxStoredPayloadsHint',
		},
	],

	buildConfig(form, editing) {
		const config: Record<string, any> = {
			auth_mode: form.auth_mode || 'none',
			payload_mappings: form.payload_mappings || [],
			store_payloads: form.store_payloads !== '0' && form.store_payloads !== 0,
			max_stored_payloads: Math.max(1, Math.min(100, Number(form.max_stored_payloads) || 20)),
		};
		if (form.webhook_secret) config.webhook_secret = form.webhook_secret;
		if (form.event_type_path) config.event_type_path = form.event_type_path;
		if (form.collection_path) config.collection_path = form.collection_path;
		return { config };
	},

	hasConfigChanged(form, existing) {
		return form.auth_mode !== (existing.auth_mode || 'none') ||
			!!form.webhook_secret ||
			(form.store_payloads !== '0' && form.store_payloads !== 0) !== (existing.store_payloads !== false) ||
			Number(form.max_stored_payloads || 20) !== Number(existing.max_stored_payloads || 20);
	},

	eventFields: [
		{ key: 'track_webhook_received', label: 'trackingConfig.webhookReceived', default: true },
	],

	collectionMeta: null,
	webhookBased: true,
	webhookUrlPattern: '/api/webhooks/webhook/{token}',
	payloadHistory: true,
};
