const config = require('config');

exports.up = async (knex) => {
	await knex.schema.alterTable('alerts', (table) => {
		table.boolean('all')
			.defaultTo(true);
	});

	await knex.schema.alterTable('alerts_entities', (table) => {
		table.dropUnique('alert_id');
	});

	await knex.schema.createTable('alerts_matches', (table) => {
		table.increments('id');

		table.integer('alert_id')
			.references('id')
			.inTable('alerts')
			.onDelete('cascade');

		table.string('property');
		table.string('expression');
	});

	await knex.raw(`
		GRANT SELECT ON alerts_matches TO :visitor;
	`, {
		visitor: knex.raw(config.database.query.user),
	});
};

exports.down = async (knex) => {
	await knex.schema.alterTable('alerts', (table) => {
		table.dropColumn('all');
	});

	await knex.schema.alterTable('alerts_entities', (table) => {
		table.unique('alert_id');
	});

	await knex.schema.dropTable('alerts_matches');
};