import { MigrationInterface, QueryRunner, TableColumn } from "typeorm";

// The FAQ library's single free-text "category" became a multi-page tag
// (an FAQ can now belong to more than one page's FAQ section) — this
// renames the column to "pages" and widens it from a 100-char plain string
// to TEXT holding a JSON array of page titles, e.g. '["Website (Landing
// Page)","SEO (Landing Page)"]'. Existing single values (legacy plain tags
// like "Website", or the page-title values from the earlier single-select
// dropdown) are wrapped in a 1-element array so every row ends up either
// NULL or a valid JSON array — see faq.service.ts, which parses this
// defensively either way.
export class RenameFaqCategoryToPages1748500000000 implements MigrationInterface {
  name = "RenameFaqCategoryToPages1748500000000";

  public async up(queryRunner: QueryRunner): Promise<void> {
    await queryRunner.renameColumn("faq_items", "category", "pages");
    await queryRunner.changeColumn(
      "faq_items",
      "pages",
      new TableColumn({ name: "pages", type: "text", isNullable: true }),
    );

    const rows: { id: string; pages: string | null }[] = await queryRunner.query(`SELECT id, pages FROM faq_items`);
    for (const row of rows) {
      if (!row.pages) continue;
      let alreadyArray = false;
      try {
        alreadyArray = Array.isArray(JSON.parse(row.pages));
      } catch {
        alreadyArray = false;
      }
      if (alreadyArray) continue;
      await queryRunner.query(`UPDATE faq_items SET pages = ? WHERE id = ?`, [JSON.stringify([row.pages]), row.id]);
    }
  }

  public async down(queryRunner: QueryRunner): Promise<void> {
    await queryRunner.renameColumn("faq_items", "pages", "category");
    await queryRunner.changeColumn(
      "faq_items",
      "category",
      new TableColumn({ name: "category", type: "varchar", length: "100", isNullable: true }),
    );
  }
}
