const config = require('config');

exports.up = async (knex) => {
	await knex.schema.alterTable('entities', (table) => {
		// internal options, as opposed to parameters for scraper options
		table.json('options');
	});

	await knex.schema.alterTable('releases', (table) => {
		table.dropForeign('entity_id');

		table.foreign('entity_id')
			.references('id')
			.inTable('entities')
			.onDelete('cascade');
	});

	await knex.schema.alterTable('releases_caps', (table) => {
		table.unique(['release_id', 'media_id']);
	});

	await knex.schema.createTable('movies_tags', (table) => {
		table.integer('tag_id')
			.references('id')
			.inTable('tags');

		table.integer('movie_id')
			.notNullable()
			.references('id')
			.inTable('movies')
			.onDelete('cascade');

		table.text('original_tag');

		table.text('source')
			.defaultTo('scraper');

		table.unique(['tag_id', 'movie_id']);
	});

	await knex.raw('GRANT ALL ON ALL TABLES IN SCHEMA public TO :visitor;', {
		visitor: knex.raw(config.database.query.user),
	});
};

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

	await knex.schema.alterTable('releases', (table) => {
		table.dropForeign('entity_id');

		table.foreign('entity_id')
			.references('id')
			.inTable('entities')
			.onDelete('no action');
	});

	await knex.schema.alterTable('releases_caps', (table) => {
		table.dropUnique(['release_id', 'media_id']);
	});

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