import { DataTypes, type QueryInterface } from 'sequelize';

/**
 * Workstream 13 — audio library. `director`/`office_manager`/`teacher` upload
 * audio files that any campus staff can pick to play in the classroom timer.
 *
 * Uploaded files are **campus-scoped** (`organizationId` + `campusId` set). The
 * existing built-in timer sounds remain the **global defaults** served from the
 * (global) `content_catalog`, so they are already available to every org and are
 * not duplicated here. `is_default` + a null `organizationId` are kept so a
 * platform admin could later add global audio rows; campus uploads are not
 * default.
 *
 * The binary itself is stored via the existing JWT-authenticated file subsystem
 * (`POST /api/file/upload/...`); `url` holds the returned reference.
 *
 * This migration is idempotent: table is only created if missing.
 */
async function tableExists(
  queryInterface: QueryInterface,
  table: string,
): Promise<boolean> {
  const [results] = await queryInterface.sequelize.query(`
    SELECT 1 FROM information_schema.tables
    WHERE table_schema = 'public' AND table_name = '${table}'
  `);
  return (results as unknown[]).length > 0;
}

export default {
  up: async (queryInterface: QueryInterface) => {
    if (await tableExists(queryInterface, 'audio_files')) {
      return;
    }

    await queryInterface.createTable('audio_files', {
      id: {
        type: DataTypes.UUID,
        defaultValue: DataTypes.UUIDV4,
        primaryKey: true,
      },
      title: { type: DataTypes.TEXT, allowNull: false },
      url: { type: DataTypes.STRING(2083), allowNull: false },
      is_default: {
        type: DataTypes.BOOLEAN,
        allowNull: false,
        defaultValue: false,
      },
      importHash: { type: DataTypes.STRING(255), allowNull: true, unique: true },
      organizationId: { type: DataTypes.UUID, allowNull: true },
      campusId: { type: DataTypes.UUID, allowNull: true },
      createdById: { type: DataTypes.UUID, allowNull: true },
      updatedById: { type: DataTypes.UUID, allowNull: true },
      createdAt: { type: DataTypes.DATE },
      updatedAt: { type: DataTypes.DATE },
      deletedAt: { type: DataTypes.DATE },
    });
  },

  down: async (queryInterface: QueryInterface) => {
    await queryInterface.dropTable('audio_files');
  },
};
