import { DataTypes, type QueryInterface } from 'sequelize';
import { USER_NAME_PREFIX_VALUES } from '@/shared/constants/users';

/**
 * Add an honorific name prefix (title) to users — `Mr.` / `Ms.` / `Dr.` etc.
 * Lets the UI render "Dr. Williams" without the title being baked into the
 * person's first name. Nullable; no production data (pre-launch reset).
 *
 * This migration is idempotent: column/enum are only added if missing.
 */
async function columnExists(
  queryInterface: QueryInterface,
  table: string,
  column: string,
): Promise<boolean> {
  const [results] = await queryInterface.sequelize.query(`
    SELECT 1 FROM information_schema.columns
    WHERE table_name = '${table}' AND column_name = '${column}'
  `);
  return (results as unknown[]).length > 0;
}

export default {
  up: async (queryInterface: QueryInterface) => {
    // Create enum type if not exists
    await queryInterface.sequelize.query(`
      DO 'BEGIN
        CREATE TYPE "public"."enum_users_name_prefix" AS ENUM(${USER_NAME_PREFIX_VALUES.map((v) => `''${v}''`).join(', ')});
      EXCEPTION WHEN duplicate_object THEN null; END';
    `);

    if (!(await columnExists(queryInterface, 'users', 'name_prefix'))) {
      await queryInterface.addColumn('users', 'name_prefix', {
        type: DataTypes.ENUM(...USER_NAME_PREFIX_VALUES),
        allowNull: true,
      });
    }
  },

  down: async (queryInterface: QueryInterface) => {
    await queryInterface.removeColumn('users', 'name_prefix');
    await queryInterface.sequelize.query(
      'DROP TYPE IF EXISTS "enum_users_name_prefix";',
    );
  },
};
