import { MigrateUpArgs, MigrateDownArgs, sql } from '@payloadcms/db-postgres'

/**
 * The counted noun gets a form per plural category, instead of one word.
 *
 * `filters_courses_count` held a single word and the site printed «4 منهج», which is wrong: in Arabic
 * a noun counted 3 to 10 takes the broken plural, «4 مناهج». One column cannot carry that, so it is
 * replaced by the five categories Intl.PluralRules distinguishes.
 *
 * Written by hand rather than generated: dropping one column and adding five in the same table makes
 * the generator ask, for each new column, whether it is a rename of the old one, and it asks through
 * a prompt that cannot be answered without a terminal. Every statement here is what answering
 * «create column» five times would have produced.
 *
 * The old word is carried into `count_other` first, so an editor who had written «كورس» keeps it as
 * the default form and nothing on the page goes blank the moment this runs.
 */
export async function up({ db }: MigrateUpArgs): Promise<void> {
  await db.execute(sql`
  ALTER TABLE "catalogue_locales" ADD COLUMN "count_one" varchar;
  ALTER TABLE "catalogue_locales" ADD COLUMN "count_two" varchar;
  ALTER TABLE "catalogue_locales" ADD COLUMN "count_few" varchar;
  ALTER TABLE "catalogue_locales" ADD COLUMN "count_many" varchar;
  ALTER TABLE "catalogue_locales" ADD COLUMN "count_other" varchar;
  UPDATE "catalogue_locales" SET "count_other" = "filters_courses_count"
    WHERE "filters_courses_count" IS NOT NULL AND "filters_courses_count" <> '';
  ALTER TABLE "catalogue_locales" DROP COLUMN IF EXISTS "filters_courses_count";`)
}

export async function down({ db }: MigrateDownArgs): Promise<void> {
  await db.execute(sql`
  ALTER TABLE "catalogue_locales" ADD COLUMN "filters_courses_count" varchar;
  UPDATE "catalogue_locales" SET "filters_courses_count" = COALESCE("count_other", "count_few", "count_one");
  ALTER TABLE "catalogue_locales" DROP COLUMN IF EXISTS "count_one";
  ALTER TABLE "catalogue_locales" DROP COLUMN IF EXISTS "count_two";
  ALTER TABLE "catalogue_locales" DROP COLUMN IF EXISTS "count_few";
  ALTER TABLE "catalogue_locales" DROP COLUMN IF EXISTS "count_many";
  ALTER TABLE "catalogue_locales" DROP COLUMN IF EXISTS "count_other";`)
}
