'use strict';

/** @type {import('sequelize-cli').Migration} */
module.exports = {
	async up(queryInterface, Sequelize) {
		return queryInterface.sequelize.transaction(async (transaction) => {
			await queryInterface.bulkDelete('favorite_folders', {
				user_id: {
					[Sequelize.Op.notIn]: Sequelize.literal('(SELECT id FROM users)'),
				},
			});

			await queryInterface.bulkDelete('favorite_folder_listings', {
				user_id: {
					[Sequelize.Op.notIn]: Sequelize.literal('(SELECT id FROM users)'),
				},
			});

			await queryInterface.bulkDelete('favorite_folder_listings', {
				folder_id: {
					[Sequelize.Op.notIn]: Sequelize.literal('(SELECT id FROM favorite_folders)'),
				},
			});

			await queryInterface.addConstraint('favorite_folders', {
				fields: ['user_id'],
				type: 'foreign key',
				name: 'fk_favorite_folders_user_id',
				references: {
					table: 'users',
					field: 'id',
				},
				onDelete: 'CASCADE',
				transaction,
			});

			await queryInterface.addConstraint('favorite_folder_listings', {
				fields: ['user_id'],
				type: 'foreign key',
				name: 'fk_favorite_folder_listings_user_id',
				references: {
					table: 'users',
					field: 'id',
				},
				onDelete: 'CASCADE',
				transaction,
			});

			await queryInterface.addConstraint('favorite_folder_listings', {
				fields: ['folder_id'],
				type: 'foreign key',
				name: 'fk_favorite_folder_listings_folder_id',
				references: {
					table: 'favorite_folders',
					field: 'id',
				},
				onDelete: 'CASCADE',
				transaction,
			});
		});
	},

	async down(queryInterface, Sequelize) {
		return queryInterface.sequelize.transaction(async (transaction) => {
			await queryInterface.removeConstraint('favorite_folders', 'fk_favorite_folders_user_id', { transaction });
			await queryInterface.removeConstraint('favorite_folder_listings', 'fk_favorite_folder_listings_user_id', {
				transaction,
			});
			await queryInterface.removeConstraint('favorite_folder_listings', 'fk_favorite_folder_listings_folder_id', {
				transaction,
			});
		});
	},
};
