import { DataTypes, type QueryInterface } from 'sequelize';
import { ROLE_SCOPE_VALUES } from '@/shared/constants/roles';

/**
 * Workstream 3 §3.1 foundation: add the authorization `scope` to `roles` (NOT
 * NULL — every role has a scope; the 11 first-class roles are seeded with one)
 * and a nullable `campusId` to `users` (campus scope for campus-bound roles;
 * null for system/organization scopes, so legitimately optional).
 *
 * Pre-launch with no production data, the `scope` column is added NOT NULL
 * against the (empty, freshly-migrated) `roles` table; seeders populate it.
 * `campusId` is a plain UUID (no DB-level FK), matching how
 * `users.organizationId` is modeled — associations use `constraints: false`.
 *
 * This migration is idempotent: columns/enums 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, then add column if not exists
    await queryInterface.sequelize.query(`
      DO 'BEGIN
        CREATE TYPE "public"."enum_roles_scope" AS ENUM(${ROLE_SCOPE_VALUES.map((v) => `''${v}''`).join(', ')});
      EXCEPTION WHEN duplicate_object THEN null; END';
    `);

    if (!(await columnExists(queryInterface, 'roles', 'scope'))) {
      await queryInterface.addColumn('roles', 'scope', {
        type: DataTypes.ENUM(...ROLE_SCOPE_VALUES),
        allowNull: false,
      });
    }

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

  down: async (queryInterface: QueryInterface) => {
    await queryInterface.removeColumn('users', 'campusId');
    await queryInterface.removeColumn('roles', 'scope');
    // Postgres keeps the enum type after the column is dropped; remove it too.
    await queryInterface.sequelize.query(
      'DROP TYPE IF EXISTS "enum_roles_scope";',
    );
  },
};
