import { MigrationInterface, QueryRunner } from 'typeorm';

export class InitialMigration1617265376698 implements MigrationInterface {
  name = 'InitialMigration1617265376698';

  public async up(queryRunner: QueryRunner): Promise<void> {
    await queryRunner.query(
      `CREATE TABLE ticket (
          id            int          NOT NULL AUTO_INCREMENT,
          name          varchar(255) NOT NULL,
          licenseeId    int          NOT NULL,
          createdOn     datetime(6) NOT NULL DEFAULT CURRENT_TIMESTAMP (6),
          updatedOn     datetime(6) NOT NULL DEFAULT CURRENT_TIMESTAMP (6) ON UPDATE CURRENT_TIMESTAMP (6),
          lastQueriedOn datetime DEFAULT NULL,
          slackThreadTs varchar(255) NOT NULL,
          PRIMARY KEY (id)
       )`
    );

    await queryRunner.query(
      `CREATE TABLE message (
          id        int          NOT NULL AUTO_INCREMENT,
          body      text         NOT NULL,
          sentBy    varchar(255) DEFAULT NULL,
          createdOn datetime(6)  NOT NULL DEFAULT CURRENT_TIMESTAMP (6),
          updatedOn datetime(6)  NOT NULL DEFAULT CURRENT_TIMESTAMP (6) ON UPDATE CURRENT_TIMESTAMP (6),
          ticketId  int          DEFAULT NULL,
          PRIMARY KEY (id),
          FOREIGN KEY (ticketId) REFERENCES ticket(id)
          )`
    );

    await queryRunner.query(
      `CREATE TABLE attachment (
          id        int          NOT NULL AUTO_INCREMENT,
          name      varchar(255) NOT NULL,
          type      varchar(255) NOT NULL,
          size      int          NOT NULL,
          url       varchar(255) NOT NULL,
          isLocal   tinyint      NOT NULL,
          messageId int DEFAULT NULL,
          PRIMARY KEY (id),
          FOREIGN KEY (messageId) REFERENCES message(id)
          )`
    );

    await queryRunner.query(
      `CREATE TABLE file (
          id               int          NOT NULL AUTO_INCREMENT,
          publicId         varchar(255) NOT NULL,
          \`key\`          varchar(255) NOT NULL,
          originalFileName varchar(255) NOT NULL,
          createdOn        datetime(6) NOT NULL DEFAULT CURRENT_TIMESTAMP (6),
          PRIMARY KEY (id)
          )`
    );
  }

  public async down(queryRunner: QueryRunner): Promise<void> {
    await queryRunner.query('DROP TABLE ticket');
    await queryRunner.query('DROP TABLE message');
    await queryRunner.query('DROP TABLE attachment');
    await queryRunner.query('DROP TABLE file');
  }
}
