import { MigrationInterface, QueryRunner } from 'typeorm';

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

  public async up(queryRunner: QueryRunner): Promise<void> {
    await queryRunner.query(`
      CREATE TABLE IF NOT EXISTS "room_owners" (
        "roomId"  TEXT NOT NULL,
        "userId"  TEXT NOT NULL,
        "savedAt" INTEGER NOT NULL,
        PRIMARY KEY ("roomId", "userId")
      )
    `);
    await queryRunner.query(`CREATE INDEX IF NOT EXISTS "idx_room_owners_userId" ON "room_owners" ("userId")`);

    const columns = await queryRunner.query(`PRAGMA table_info("messages")`) as Array<{ name?: string }>;
    const hasOwnerUserId = columns.some((column) => column.name === 'ownerUserId');

    if (!hasOwnerUserId) {
      await queryRunner.query(`ALTER TABLE "messages" ADD COLUMN "ownerUserId" TEXT`);
    }

    await queryRunner.query(`CREATE INDEX IF NOT EXISTS "idx_messages_owner_room" ON "messages" ("ownerUserId", "roomId")`);

    const metaRows = await queryRunner.query(`SELECT "value" FROM "meta" WHERE "key" = 'currentUserId' LIMIT 1`) as Array<{ value?: string | null }>;
    const currentUserId = metaRows[0]?.value?.trim();

    if (!currentUserId) {
      return;
    }

    const now = Date.now();

    await queryRunner.query(
      `INSERT OR IGNORE INTO "room_owners" ("roomId", "userId", "savedAt") SELECT "id", ?, ? FROM "rooms"`,
      [currentUserId, now]
    );
    await queryRunner.query(
      `UPDATE "messages" SET "ownerUserId" = ? WHERE "ownerUserId" IS NULL`,
      [currentUserId]
    );
  }

  public async down(queryRunner: QueryRunner): Promise<void> {
    await queryRunner.query(`DROP INDEX IF EXISTS "idx_messages_owner_room"`);
    await queryRunner.query(`DROP INDEX IF EXISTS "idx_room_owners_userId"`);
    await queryRunner.query(`DROP TABLE IF EXISTS "room_owners"`);
  }
}