'use strict';

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

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

			await queryInterface.addConstraint('listing_add_ons', {
				type: 'foreign key',
				fields: ['listing_id'],
				references: {
					table: 'listings',
					field: 'id',
				},
				onDelete: 'CASCADE',
				name: 'listing_add_ons_listing_id_foreign_key',
				transaction,
			});

			await queryInterface.addConstraint('listing_images', {
				type: 'foreign key',
				fields: ['listing_id'],
				references: {
					table: 'listings',
					field: 'id',
				},
				onDelete: 'CASCADE',
				name: 'listing_images_listing_id_foreign_key',
				transaction,
			});
		});
	},

	async down(queryInterface, Sequelize) {
		return queryInterface.sequelize.transaction(async (transaction) => {
			await queryInterface.removeConstraint('listings', 'listings_host_id_foreign_key', { transaction });
			await queryInterface.removeConstraint('listing_add_ons', 'listing_add_ons_listing_id_foreign_key', {
				transaction,
			});
			await queryInterface.removeConstraint('listing_images', 'listing_images_listing_id_foreign_key', { transaction });
		});
	},
};
