import { Migration } from '@mikro-orm/migrations';

export class Migration20240415134130 extends Migration {

  async up(): Promise<void> {
    this.addSql('create table "app" ("id" serial primary key, "created_at" timestamptz not null, "updated_at" timestamptz not null, "name" varchar(255) not null);');

    this.addSql('create table "tenant" ("id" serial primary key, "created_at" timestamptz not null, "updated_at" timestamptz not null, "name" varchar(255) not null);');

    this.addSql('create table "user" ("id" serial primary key, "created_at" timestamptz not null, "updated_at" timestamptz not null, "username" varchar(255) not null);');

    this.addSql('create table "tenant_app" ("id" serial primary key, "created_at" timestamptz not null, "updated_at" timestamptz not null, "tenant_id" int not null, "app_id" int not null, "user_id" int not null);');

    this.addSql('create table "apikey" ("id" serial primary key, "created_at" timestamptz not null, "updated_at" timestamptz not null, "key" varchar(255) not null, "user_id" int not null, "app_id" int not null);');

    this.addSql('alter table "tenant_app" add constraint "tenant_app_tenant_id_foreign" foreign key ("tenant_id") references "tenant" ("id") on update cascade;');
    this.addSql('alter table "tenant_app" add constraint "tenant_app_app_id_foreign" foreign key ("app_id") references "app" ("id") on update cascade;');
    this.addSql('alter table "tenant_app" add constraint "tenant_app_user_id_foreign" foreign key ("user_id") references "user" ("id") on update cascade;');

    this.addSql('alter table "apikey" add constraint "apikey_user_id_foreign" foreign key ("user_id") references "user" ("id") on update cascade;');
    this.addSql('alter table "apikey" add constraint "apikey_app_id_foreign" foreign key ("app_id") references "app" ("id") on update cascade;');
  }

  async down(): Promise<void> {
    this.addSql('alter table "tenant_app" drop constraint "tenant_app_app_id_foreign";');

    this.addSql('alter table "tenant_app" drop constraint "tenant_app_tenant_id_foreign";');

    this.addSql('alter table "tenant_app" drop constraint "tenant_app_user_id_foreign";');

    this.addSql('alter table "apikey" drop constraint "apikey_user_id_foreign";');
    this.addSql('alter table "apikey" drop constraint "apikey_app_id_foreign";');

    this.addSql('drop table if exists "app" cascade;');

    this.addSql('drop table if exists "tenant" cascade;');

    this.addSql('drop table if exists "user" cascade;');

    this.addSql('drop table if exists "tenant_app" cascade;');

    this.addSql('drop table if exists "apikey" cascade;');
  }

}
