import { MigrationInterface, QueryRunner } from 'typeorm';

export class addComments1715744213647 implements MigrationInterface {
  public async up(queryRunner: QueryRunner): Promise<void> {
    await queryRunner.query(`
        CREATE TABLE comments(
            id uuid NOT NULL,
            project_id BIGINT NOT NULL references projects(id) ON UPDATE CASCADE ON DELETE CASCADE,
            created_at  timestamp with time zone default now() not null,
            updated_at  timestamp with time zone,
            deleted_at  timestamp with time zone,
            PRIMARY KEY(project_id, id)  
        )          
    `);

    await queryRunner.query(`
        CREATE TABLE comment_replies(
            id uuid NOT NULL,
            changed_to_id uuid,
            answer_to_id uuid,
            project_id BIGINT NOT NULL references projects(id) ON UPDATE CASCADE ON DELETE CASCADE,
            comment_id uuid NOT NULL,
            user_id BIGINT NOT NULL,
            content JSONB NOT NULL,
            created_at  timestamp with time zone default now() not null,
            updated_at  timestamp with time zone,
            deleted_at  timestamp with time zone,
            PRIMARY KEY(project_id, comment_id, id),
            foreign key (project_id, comment_id, changed_to_id) references comment_replies(project_id, comment_id, id) ON UPDATE CASCADE ON DELETE CASCADE,
            foreign key (project_id, comment_id, answer_to_id) references comment_replies(project_id, comment_id, id) ON UPDATE CASCADE ON DELETE CASCADE,
            foreign key (project_id, comment_id) references comments(project_id, id) ON UPDATE CASCADE ON DELETE CASCADE
        )  
    `);

    await queryRunner.query(`
        CREATE TABLE comment_block_keys(
            project_id BIGINT NOT NULL references projects(id) ON UPDATE CASCADE ON DELETE CASCADE,
            asset_id UUID NOT NULL,
            block_key BIGINT NOT NULL,
            comment_id UUID NOT NULL,
            anchor JSONB,
            PRIMARY KEY(project_id, asset_id, comment_id),
            foreign key (project_id, asset_id) references assets(project_id, id) ON UPDATE CASCADE ON DELETE CASCADE        
        )          
    `);
  }

  public async down(queryRunner: QueryRunner): Promise<void> {
    await queryRunner.query(`
        DROP TABLE comment_block_keys
    `);
    await queryRunner.query(`
        DROP TABLE comment_replies
    `);
    await queryRunner.query(`
        DROP TABLE comments
    `);
  }
}
