import { sql, type Kysely } from "kysely";

/**
 * Console-wide settings, keyed by name.
 *
 * Added for the promo appearance theme. That theme was stored in each browser's
 * localStorage, which made it a per-device preference: a super admin picking an
 * accent changed it only on their own machine. The intent is the opposite — one
 * super admin sets the look and every console user sees it — so the value has to
 * live server-side.
 *
 * Deliberately a generic key/value table rather than a `promo_theme` table: the
 * value is a small JSON blob whose shape is owned by the client, and other
 * console-wide settings can reuse the same row format instead of each needing a
 * migration.
 */
export async function up(db: Kysely<any>): Promise<void> {
  await db.schema
    .createTable("console_settings")
    .ifNotExists()
    .addColumn("id", "serial", (col) => col.primaryKey())
    // One row per setting; the unique constraint is what makes the write an
    // upsert rather than a read-then-insert race.
    .addColumn("key", "varchar(120)", (col) => col.notNull().unique())
    .addColumn("value", "jsonb", (col) => col.notNull())
    .addColumn("updated_at", "timestamptz", (col) =>
      col.notNull().defaultTo(sql`now()`),
    )
    // Who last changed it, for the activity trail. Nullable and not a foreign
    // key so removing a console user never blocks reading a setting.
    .addColumn("updated_by", "varchar(120)")
    .execute();
}

export async function down(db: Kysely<any>): Promise<void> {
  await db.schema.dropTable("console_settings").ifExists().execute();
}
