import { MigrationInterface, QueryRunner } from 'typeorm';

export class ServerAccessControl1000000000001 implements MigrationInterface {
  name = 'ServerAccessControl1000000000001';

  public async up(queryRunner: QueryRunner): Promise<void> {
    await queryRunner.query(`ALTER TABLE "servers" ADD COLUMN "passwordHash" TEXT`);

    await queryRunner.query(`
      CREATE TABLE IF NOT EXISTS "server_memberships" (
        "id"           TEXT PRIMARY KEY NOT NULL,
        "serverId"     TEXT NOT NULL,
        "userId"       TEXT NOT NULL,
        "joinedAt"     INTEGER NOT NULL,
        "lastAccessAt" INTEGER NOT NULL
      )
    `);
    await queryRunner.query(`CREATE INDEX IF NOT EXISTS "idx_server_memberships_serverId" ON "server_memberships" ("serverId")`);
    await queryRunner.query(`CREATE INDEX IF NOT EXISTS "idx_server_memberships_userId" ON "server_memberships" ("userId")`);

    await queryRunner.query(`
      CREATE TABLE IF NOT EXISTS "server_invites" (
        "id"                   TEXT PRIMARY KEY NOT NULL,
        "serverId"             TEXT NOT NULL,
        "createdBy"            TEXT NOT NULL,
        "createdByDisplayName" TEXT,
        "createdAt"            INTEGER NOT NULL,
        "expiresAt"            INTEGER NOT NULL
      )
    `);
    await queryRunner.query(`CREATE INDEX IF NOT EXISTS "idx_server_invites_serverId" ON "server_invites" ("serverId")`);
    await queryRunner.query(`CREATE INDEX IF NOT EXISTS "idx_server_invites_expiresAt" ON "server_invites" ("expiresAt")`);

    await queryRunner.query(`
      CREATE TABLE IF NOT EXISTS "server_bans" (
        "id"          TEXT PRIMARY KEY NOT NULL,
        "serverId"    TEXT NOT NULL,
        "userId"      TEXT NOT NULL,
        "bannedBy"    TEXT NOT NULL,
        "displayName" TEXT,
        "reason"      TEXT,
        "expiresAt"   INTEGER,
        "createdAt"   INTEGER NOT NULL
      )
    `);
    await queryRunner.query(`CREATE INDEX IF NOT EXISTS "idx_server_bans_serverId" ON "server_bans" ("serverId")`);
    await queryRunner.query(`CREATE INDEX IF NOT EXISTS "idx_server_bans_userId" ON "server_bans" ("userId")`);
  }

  public async down(queryRunner: QueryRunner): Promise<void> {
    await queryRunner.query(`DROP TABLE IF EXISTS "server_bans"`);
    await queryRunner.query(`DROP TABLE IF EXISTS "server_invites"`);
    await queryRunner.query(`DROP TABLE IF EXISTS "server_memberships"`);
    await queryRunner.query(`ALTER TABLE "servers" DROP COLUMN "passwordHash"`);
  }
}
