import { MigrationInterface, QueryRunner } from 'typeorm';

export class AddNotificationTables1785600000000 implements MigrationInterface {
  name = 'AddNotificationTables1785600000000';

  public async up(queryRunner: QueryRunner): Promise<void> {
    await queryRunner.query(`
      CREATE TABLE "notification" (
        "id" SERIAL NOT NULL,
        "teamId" integer NOT NULL,
        "event" character varying NOT NULL,
        "actorUserId" integer NOT NULL,
        "payload" text NOT NULL,
        "createdAt" TIMESTAMP NOT NULL DEFAULT now(),
        CONSTRAINT "PK_notification_id" PRIMARY KEY ("id")
      )
    `);
    await queryRunner.query(
      `CREATE INDEX "IDX_notification_team_id" ON "notification" ("teamId")`,
    );
    await queryRunner.query(`
      ALTER TABLE "notification"
      ADD CONSTRAINT "FK_notification_team"
      FOREIGN KEY ("teamId") REFERENCES "team"("id")
      ON DELETE CASCADE
    `);

    await queryRunner.query(`
      CREATE TABLE "notification_recipient" (
        "id" SERIAL NOT NULL,
        "notificationId" integer NOT NULL,
        "userId" integer NOT NULL,
        "read" boolean NOT NULL DEFAULT false,
        "readAt" TIMESTAMP,
        CONSTRAINT "PK_notification_recipient_id" PRIMARY KEY ("id")
      )
    `);
    await queryRunner.query(
      `CREATE INDEX "IDX_notification_recipient_notification_id" ON "notification_recipient" ("notificationId")`,
    );
    await queryRunner.query(
      `CREATE INDEX "IDX_notification_recipient_user_id" ON "notification_recipient" ("userId")`,
    );
    await queryRunner.query(`
      ALTER TABLE "notification_recipient"
      ADD CONSTRAINT "FK_notification_recipient_notification"
      FOREIGN KEY ("notificationId") REFERENCES "notification"("id")
      ON DELETE CASCADE
    `);
  }

  public async down(queryRunner: QueryRunner): Promise<void> {
    await queryRunner.query(`DROP TABLE "notification_recipient"`);
    await queryRunner.query(`DROP TABLE "notification"`);
  }
}
