import { FSDB_COLLECTION } from '@andyburke/fsdb';
import { by_lurid } from '@andyburke/fsdb/organizers';
import { FSDB_INDEXER_SYMLINKS } from '@andyburke/fsdb/indexers';

/**
 * @typedef {object} WATCH_TIMESTAMPS
 * @property {string}	created			the created date of the watch
 * @property {string}	updated			the last updated date, usually coinciding with the last seen id being changed
 */

export type WATCH_TIMESTAMPS = {
	created: string;
	updated: string;
};

/**
 * WATCH
 *
 * @property {string} id						- lurid (stable)
 * @property {string} creator_id				- user id of the watch creator
 * @property {string} [type]					- a filter for event type
 * @property {string} [parent_id]				- a filter for event parent_id
 * @property {string} [channel]					- a filter for event channel
 * @property {string} [topic]					- a filter for event topic
 * @property {string[]} [tags]					- a filter for event tags
 * @property {Record<string,any>} [data]		- a filter on event data, each leaf should be a RegExp
 * @property {string} last_id_seen				- the last id the user has seen for this watch
 * @property {string} [last_id_notified]		- the last id the user was notified about for this watch
 * @property {Record<string,any>} [meta]		- optional metadata about the watch
 * @property {WATCH_TIMESTAMPS} timestamps		- timestamps for the watch
 */

export type WATCH = {
	id: string;
	creator_id: string;
	type?: string;
	parent_id?: string;
	channel?: string;
	topic?: string;
	tags?: string[];
	data?: Record<string, any>;
	last_id_seen: string;
	last_id_notified?: string;
	meta?: Record<string, any>;
	timestamps: WATCH_TIMESTAMPS;
};

export const WATCHES = new FSDB_COLLECTION<WATCH>({
	name: 'watches',
	id_field: 'id',
	organize: by_lurid,
	indexers: {
		creator_id: new FSDB_INDEXER_SYMLINKS<WATCH>({
			name: 'creator_id',
			field: 'creator_id',
			to_many: true,
			organize: by_lurid
		}),

		type: new FSDB_INDEXER_SYMLINKS<WATCH>({
			name: 'type',
			field: 'type',
			to_many: true,
			organize: (type: string) => [type],
			organize_id: by_lurid
		}),

		parent_id: new FSDB_INDEXER_SYMLINKS<WATCH>({
			name: 'parent_id',
			field: 'parent_id',
			to_many: true,
			organize: by_lurid,
			organize_id: by_lurid
		}),

		channel: new FSDB_INDEXER_SYMLINKS<WATCH>({
			name: 'channel',
			field: 'channel',
			to_many: true,
			organize: (channel: string) => channel.length > 3 ? [channel.substring(0, 3), channel] : [channel],
			organize_id: by_lurid
		}),

		topic: new FSDB_INDEXER_SYMLINKS<WATCH>({
			name: 'topic',
			field: 'topic',
			to_many: true,
			organize: (topic: string) => topic.length > 3 ? [topic.substring(0, 3), topic] : [topic],
			organize_id: by_lurid
		}),

		tags: new FSDB_INDEXER_SYMLINKS<WATCH>({
			name: 'tags',
			field: 'tags',
			to_many: true,
			organize: (tag: string) => tag.length > 3 ? [tag.substring(0, 3), tag] : [tag],
			organize_id: by_lurid
		})
	}
});
