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

/**
 * @typedef {object} CHANNEL_EVENT_PERMISSIONS
 * @property {string[]}	read						a list of user_ids with read permission for the channel events
 * @property {string[]} write						a list of user_ids with write permission for the channel events
 */

/**
 * @typedef {object} CHANNEL_PERMISSIONS
 * @property {string[]}	read						a list of user_ids with read permission for the channel
 * @property {string[]} write						a list of user_ids with write permission for the channel
 * @property {CHANNEL_EVENT_PERMISSIONS} events
 */

/**
 * @typedef {object} CHANNEL_TIMESTAMPS
 * @property {string}	created						when the channel was created
 * @property {string}	updated						the last time the channel was updated
 * @property {string}	[archived]					an option time the channel was archived
 */

/**
 * CHANNEL
 *
 * @property {string} id						- lurid (stable)
 * @property {string} name						- channel name (max 64 characters, unique, unstable)
 * @property {string} creator_id				- user id of the channel creator
 * @property {CHANNEL_PERMISSIONS} permissions	- permissions setup for the channel
 * @property {string} [icon]					- optional url for channel icon
 * @property {string} [topic]					- optional topic for the channel
 * @property {string} [rules]					- optional channel rules (Markdown/text)
 * @property {string[]} [tags]					- optional tags for the channel
 * @property {Record<string,any>} [meta]		- optional metadata about the channel
 * @property {CHANNEL_TIMESTAMPS} timestamps	- timestamps
 */

export type CHANNEL = {
	id: string;
	name: string;
	creator_id: string;
	permissions: {
		read: string[];
		write: string[];
		events: {
			read: string[];
			write: string[];
		};
	};
	icon?: string;
	topic?: string;
	rules?: string;
	tags?: string[];
	meta?: Record<string, any>;
	timestamps: {
		created: string;
		updated: string;
		archived: string | undefined;
	};
};

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

		name: new FSDB_INDEXER_SYMLINKS<CHANNEL>({
			name: 'name',
			get_values_to_index: (channel) => [channel.name.toLowerCase()],
			organize: by_character
		}),

		tags: new FSDB_INDEXER_SYMLINKS<CHANNEL>({
			name: 'tags',
			get_values_to_index: (channel): string[] => {
				return (channel.tags ?? []).map((tag) => tag.toLowerCase());
			},
			to_many: true,
			organize: by_character
		})
	}
});
