import { MigrationInterface, QueryRunner } from 'typeorm';

export class updateStructure1700409239334 implements MigrationInterface {
  public async up(queryRunner: QueryRunner): Promise<void> {
    await queryRunner.query(`DROP TABLE files`);
    await queryRunner.query(
      `
        create table contents
        (
            id uuid not null,
            store varchar not null,
            hash varchar not null,
            size bigint not null,
            primary key (store, id)
        );
        `,
    );
    await queryRunner.query(
      `CREATE UNIQUE INDEX contents_uniq ON contents(store, hash)`,
    );
    await queryRunner.query(
      `
        create table files
        (
            id uuid not null,
            content_id uuid not null,
            store varchar not null,
            title varchar not null,
            dir varchar,
            uploaded_by varchar not null,
            uploaded_at timestamp with time zone default now() not null,
            is_secret boolean default false not null,
            primary key (store, id),
            FOREIGN KEY (store, content_id) REFERENCES contents(store, id) ON DELETE CASCADE ON UPDATE CASCADE
        );
        `,
    );
    await queryRunner.query(
      `CREATE INDEX files_content_indx ON files(store, content_id)`,
    );
    await queryRunner.query(`CREATE INDEX files_dir_indx ON files(store, dir)`);
  }

  public async down(queryRunner: QueryRunner): Promise<void> {
    await queryRunner.query(`DROP TABLE files`);
    await queryRunner.query(`DROP TABLE contents`);
    await queryRunner.query(
      `
        create table files
        (
            id uuid not null
                constraint files_pkey
                    primary key,
            title varchar not null,
            is_secret boolean default false not null,
            size integer not null,
            project_id varchar,
            dir varchar,
            quota integer,
            rights varchar,
            uploaded_at timestamp with time zone default now() not null,
            deleted_at timestamp with time zone
        );
        `,
    );
  }
}
