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

/**
 * Bridge self-monitoring provider descriptor.
 *
 * The bridge_self provider has no remote URL and no credentials. The only
 * configuration surface is the three thresholds below, used by the server
 * to decide when an internal failure deserves a notification.
 *
 * Exactly one bridge_self provider exists per user, auto-seeded on user
 * creation (see ``packages/server/src/notify_bridge_server/database/seeds.py``).
 */
export const bridgeSelfDescriptor: ProviderDescriptor = {
	type: 'bridge_self',
	defaultName: 'Bridge Self-Monitoring',
	icon: 'mdiAlertCircleOutline',
	hasUrl: false,

	configFields: [
		{
			key: 'poll_failure_threshold',
			configKey: 'poll_failure_threshold',
			label: 'providers.bridgeSelfPollThreshold',
			type: 'number',
			optional: true,
			min: 1,
			defaultValue: 3,
			hint: 'providers.bridgeSelfPollThresholdHint',
		},
		{
			key: 'deferred_backlog_threshold',
			configKey: 'deferred_backlog_threshold',
			label: 'providers.bridgeSelfDeferredThreshold',
			type: 'number',
			optional: true,
			min: 1,
			defaultValue: 100,
			hint: 'providers.bridgeSelfDeferredThresholdHint',
		},
		{
			key: 'target_failure_threshold',
			configKey: 'target_failure_threshold',
			label: 'providers.bridgeSelfTargetThreshold',
			type: 'number',
			optional: true,
			min: 1,
			defaultValue: 5,
			hint: 'providers.bridgeSelfTargetThresholdHint',
		},
	],

	buildConfig(form) {
		const toInt = (raw: unknown, fallback: number): number => {
			const n = typeof raw === 'number' ? raw : parseInt(String(raw ?? ''), 10);
			return Number.isFinite(n) && n >= 1 ? n : fallback;
		};
		return {
			config: {
				poll_failure_threshold: toInt(form.poll_failure_threshold, 3),
				deferred_backlog_threshold: toInt(form.deferred_backlog_threshold, 100),
				target_failure_threshold: toInt(form.target_failure_threshold, 5),
			},
		};
	},

	hasConfigChanged(form, existing) {
		const toInt = (raw: unknown, fallback: number): number => {
			const n = typeof raw === 'number' ? raw : parseInt(String(raw ?? ''), 10);
			return Number.isFinite(n) && n >= 1 ? n : fallback;
		};
		return (
			toInt(form.poll_failure_threshold, 3) !== toInt(existing.poll_failure_threshold, 3) ||
			toInt(form.deferred_backlog_threshold, 100) !== toInt(existing.deferred_backlog_threshold, 100) ||
			toInt(form.target_failure_threshold, 5) !== toInt(existing.target_failure_threshold, 5)
		);
	},

	eventFields: [
		{
			key: 'track_bridge_self_poll_failures',
			label: 'trackingConfig.bridgeSelfPollFailures',
			default: true,
		},
		{
			key: 'track_bridge_self_deferred_backlog',
			label: 'trackingConfig.bridgeSelfDeferredBacklog',
			default: true,
		},
		{
			key: 'track_bridge_self_target_failures',
			label: 'trackingConfig.bridgeSelfTargetFailures',
			default: true,
		},
	],

	collectionMeta: null,
	webhookBased: false,
};
