import { MigrationInterface, QueryRunner } from 'typeorm';

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

  public async up(queryRunner: QueryRunner): Promise<void> {
    await queryRunner.query(`
      CREATE TABLE IF NOT EXISTS "users" (
        "id"           TEXT PRIMARY KEY NOT NULL,
        "username"     TEXT UNIQUE NOT NULL,
        "passwordHash" TEXT NOT NULL,
        "displayName"  TEXT NOT NULL,
        "createdAt"    INTEGER NOT NULL
      )
    `);

    await queryRunner.query(`
      CREATE TABLE IF NOT EXISTS "servers" (
        "id"             TEXT PRIMARY KEY NOT NULL,
        "name"           TEXT NOT NULL,
        "description"    TEXT,
        "ownerId"        TEXT NOT NULL,
        "ownerPublicKey" TEXT NOT NULL,
        "isPrivate"      INTEGER NOT NULL DEFAULT 0,
        "maxUsers"       INTEGER NOT NULL DEFAULT 0,
        "currentUsers"   INTEGER NOT NULL DEFAULT 0,
        "tags"           TEXT NOT NULL DEFAULT '[]',
        "channels"       TEXT NOT NULL DEFAULT '[]',
        "createdAt"      INTEGER NOT NULL,
        "lastSeen"       INTEGER NOT NULL
      )
    `);

    await queryRunner.query(`
      CREATE TABLE IF NOT EXISTS "join_requests" (
        "id"           TEXT PRIMARY KEY NOT NULL,
        "serverId"     TEXT NOT NULL,
        "userId"       TEXT NOT NULL,
        "userPublicKey" TEXT NOT NULL,
        "displayName"  TEXT NOT NULL,
        "status"       TEXT NOT NULL DEFAULT 'pending',
        "createdAt"    INTEGER NOT NULL
      )
    `);

    await queryRunner.query(`CREATE INDEX IF NOT EXISTS "idx_join_requests_serverId" ON "join_requests" ("serverId")`);
  }

  public async down(queryRunner: QueryRunner): Promise<void> {
    await queryRunner.query(`DROP TABLE IF EXISTS "join_requests"`);
    await queryRunner.query(`DROP TABLE IF EXISTS "servers"`);
    await queryRunner.query(`DROP TABLE IF EXISTS "users"`);
  }
}
