import { MigrationInterface, QueryRunner } from 'typeorm';

export class updateAssetHistory1697869653800 implements MigrationInterface {
  public async up(queryRunner: QueryRunner): Promise<void> {
    await queryRunner.query(`DROP TABLE public.asset_changes`);
    await queryRunner.query(
      `create table if not exists public.asset_changes (
            project_id BIGINT not null
                constraint project_fkey
                    references public.projects
                    on update cascade on delete restrict,
            id UUID not null,
            user_id integer not null REFERENCES users(id) ON UPDATE CASCADE ON DELETE RESTRICT,
            created_at timestamptz default now() not null,
            PRIMARY KEY(project_id, id)
        );`,
    );
    await queryRunner.query(
      `create table if not exists public.asset_change_assets (      
        project_id BIGINT not null
            constraint project_fkey
                references public.projects
                on update cascade on delete restrict,
        change_id UUID not null,
        asset_id UUID not null,
        redo_change JSONB not null,
        undo_change JSONB not null,
        PRIMARY KEY(project_id, change_id, asset_id),
        foreign key (project_id, asset_id) references assets(project_id, id) ON UPDATE CASCADE ON DELETE CASCADE,
        foreign key (project_id, change_id) references asset_changes(project_id, id) ON UPDATE CASCADE ON DELETE CASCADE
    );`,
    );
  }

  public async down(queryRunner: QueryRunner): Promise<void> {
    await queryRunner.query(`DROP TABLE public.asset_change_assets`);
    await queryRunner.query(`DROP TABLE public.asset_changes`);
    await queryRunner.query(
      `create table if not exists public.asset_changes (
            project_id BIGINT not null
                constraint project_fkey
                    references public.projects
                    on update cascade on delete restrict,
            change_id UUID not null,
            asset_id UUID not null,
            block_key BIGINT,
            undo_change JSONB not null,
            redo_change JSONB not null,
            user_id integer not null REFERENCES users(id) ON UPDATE CASCADE ON DELETE RESTRICT,
            created_at timestamptz default now() not null,
            PRIMARY KEY(project_id, change_id, asset_id),
            foreign key (project_id, asset_id) references assets(project_id, id) ON UPDATE CASCADE ON DELETE CASCADE
        );`,
    );
    await queryRunner.query(
      `CREATE INDEX asset_changes_asset ON asset_changes(asset_id, created_at);`,
    );
  }
}
