import { MigrationInterface, QueryRunner } from 'typeorm'

export class AddOrderTableEntity1722595374654 implements MigrationInterface {
	name = 'AddOrderTableEntity1722595374654'

	public async up(queryRunner: QueryRunner): Promise<void> {
		await queryRunner.query(
			`CREATE TABLE "order_tables" ("orderId" uuid NOT NULL, "tableId" uuid NOT NULL, CONSTRAINT "PK_d73008e7231de22fa1468c98534" PRIMARY KEY ("orderId", "tableId"))`,
		)
		await queryRunner.query(`CREATE INDEX "IDX_2f49f90a675d46055c0c0cc053" ON "order_tables" ("orderId") `)
		await queryRunner.query(`CREATE INDEX "IDX_a3989a36575006d66dd0f347bf" ON "order_tables" ("tableId") `)
		await queryRunner.query(`ALTER TABLE "order" DROP CONSTRAINT "FK_a9757413db9333d4bb21a2a42aa"`)
		await queryRunner.query(`ALTER TABLE "order" ALTER COLUMN "tableId" DROP NOT NULL`)
		await queryRunner.query(
			`ALTER TABLE "order" ADD CONSTRAINT "FK_a9757413db9333d4bb21a2a42aa" FOREIGN KEY ("tableId") REFERENCES "table"("id") ON DELETE NO ACTION ON UPDATE NO ACTION`,
		)
		await queryRunner.query(
			`ALTER TABLE "order_tables" ADD CONSTRAINT "FK_2f49f90a675d46055c0c0cc053c" FOREIGN KEY ("orderId") REFERENCES "order"("id") ON DELETE CASCADE ON UPDATE CASCADE`,
		)
		await queryRunner.query(
			`ALTER TABLE "order_tables" ADD CONSTRAINT "FK_a3989a36575006d66dd0f347bfd" FOREIGN KEY ("tableId") REFERENCES "table"("id") ON DELETE CASCADE ON UPDATE CASCADE`,
		)
	}

	public async down(queryRunner: QueryRunner): Promise<void> {
		await queryRunner.query(`ALTER TABLE "order_tables" DROP CONSTRAINT "FK_a3989a36575006d66dd0f347bfd"`)
		await queryRunner.query(`ALTER TABLE "order_tables" DROP CONSTRAINT "FK_2f49f90a675d46055c0c0cc053c"`)
		await queryRunner.query(`ALTER TABLE "order" DROP CONSTRAINT "FK_a9757413db9333d4bb21a2a42aa"`)
		await queryRunner.query(`ALTER TABLE "order" ALTER COLUMN "tableId" SET NOT NULL`)
		await queryRunner.query(
			`ALTER TABLE "order" ADD CONSTRAINT "FK_a9757413db9333d4bb21a2a42aa" FOREIGN KEY ("tableId") REFERENCES "table"("id") ON DELETE NO ACTION ON UPDATE NO ACTION`,
		)
		await queryRunner.query(`DROP INDEX "public"."IDX_a3989a36575006d66dd0f347bf"`)
		await queryRunner.query(`DROP INDEX "public"."IDX_2f49f90a675d46055c0c0cc053"`)
		await queryRunner.query(`DROP TABLE "order_tables"`)
	}
}
