'use strict';

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

			await queryInterface.bulkDelete('host_registration_add_ons', {
				host_registration_id: {
					[Sequelize.Op.notIn]: Sequelize.literal('(SELECT id FROM host_registrations)'),
				},
			});

			await queryInterface.bulkDelete('host_registration_files', {
				host_registration_id: {
					[Sequelize.Op.notIn]: Sequelize.literal('(SELECT id FROM host_registrations)'),
				},
			});

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

			await queryInterface.addConstraint('host_notifications', {
				fields: ['host_id'],
				type: 'foreign key',
				name: 'fk_host_notifications_host_id',
				references: {
					table: 'users',
					field: 'id',
				},
				onDelete: 'cascade',
				transaction,
			});

			await queryInterface.addConstraint('host_registration_add_ons', {
				fields: ['host_registration_id'],
				type: 'foreign key',
				name: 'fk_host_registration_add_ons_host_registration_id',
				references: {
					table: 'host_registrations',
					field: 'id',
				},
				onDelete: 'cascade',
				transaction,
			});

			await queryInterface.addConstraint('host_registration_files', {
				fields: ['host_registration_id'],
				type: 'foreign key',
				name: 'fk_host_registration_files_host_registration_id',
				references: {
					table: 'host_registrations',
					field: 'id',
				},
				onDelete: 'cascade',
				transaction,
			});
		});
	},

	async down(queryInterface, Sequelize) {
		return queryInterface.sequelize.transaction(async (transaction) => {
			await queryInterface.removeConstraint('host_registrations', 'fk_host_registrations_user_id', { transaction });
			await queryInterface.removeConstraint('host_notifications', 'fk_host_notifications_host_id', { transaction });
			await queryInterface.removeConstraint(
				'host_registration_add_ons',
				'fk_host_registration_add_ons_host_registration_id',
				{ transaction },
			);
			await queryInterface.removeConstraint(
				'host_registration_files',
				'fk_host_registration_files_host_registration_id',
				{ transaction },
			);
		});
	},
};
