import { MigrationInterface, QueryRunner } from 'typeorm';

export class updateAssetReferencies1698787395585 implements MigrationInterface {
  public async up(queryRunner: QueryRunner): Promise<void> {
    await queryRunner.query(`
        drop table asset_references;
        
        create table asset_references
        (
            project_id bigint not null,
            asset_id uuid not null,
            target_asset_id uuid not null,
            block_key bigint not null,
            target_block_key bigint not null,
            created_at timestamptz default now() not null,
            constraint asset_references_pkey
                primary key (project_id, asset_id, block_key, target_asset_id, target_block_key)
        );

        create index if not exists asset_references_target
        on asset_references (project_id, target_asset_id, target_block_key);
    `);
  }

  public async down(queryRunner: QueryRunner): Promise<void> {
    await queryRunner.query(`
            drop table asset_references
        `);
    await queryRunner.query(`
            create table asset_references
            (
                project_id bigint not null,
                id uuid not null,
                source_asset_id uuid not null,
                target_asset_id uuid not null,
                source_block_key bigint,
                target_block_key bigint,
                constraint asset_references_pkey
                    primary key (project_id, id),
                constraint asset_references_project_id_source_asset_id_fkey
                    foreign key (project_id, source_asset_id) references assets
                        on update cascade on delete cascade,
                constraint asset_references_project_id_target_asset_id_fkey
                    foreign key (project_id, target_asset_id) references assets
                        on update cascade on delete cascade,
                constraint asset_references_project_id_source_block_key_fkey
                    foreign key (project_id, source_block_key) references asset_block_keys
                        on update cascade on delete cascade,
                constraint asset_references_project_id_target_block_key_fkey
                    foreign key (project_id, target_block_key) references asset_block_keys
                        on update cascade on delete cascade
            );
        `);
  }
}
