import { QueryInterface, DataTypes } from 'sequelize';

export async function up(queryInterface: QueryInterface): Promise<void> {
  await queryInterface.sequelize.query(`DO $$
  BEGIN
    IF NOT EXISTS (SELECT 1 FROM pg_type WHERE typname = 'enum_participant_type') THEN
      CREATE TYPE enum_participant_type AS ENUM ('SPECTATOR','INITIATOR','APPROVER','CONSULTATION');
    END IF;
  END$$;`);

  await queryInterface.createTable('participants', {
    participant_id: { type: DataTypes.UUID, primaryKey: true, defaultValue: DataTypes.UUIDV4 },
    request_id: { type: DataTypes.UUID, allowNull: false, references: { model: 'workflow_requests', key: 'request_id' } },
    user_id: { type: DataTypes.UUID, allowNull: false, references: { model: 'users', key: 'user_id' } },
    user_email: { type: DataTypes.STRING(255), allowNull: false },
    user_name: { type: DataTypes.STRING(200), allowNull: false },
    participant_type: { type: 'enum_participant_type' as any, allowNull: false },
    can_comment: { type: DataTypes.BOOLEAN, allowNull: false, defaultValue: true },
    can_view_documents: { type: DataTypes.BOOLEAN, allowNull: false, defaultValue: true },
    can_download_documents: { type: DataTypes.BOOLEAN, allowNull: false, defaultValue: false },
    notification_enabled: { type: DataTypes.BOOLEAN, allowNull: false, defaultValue: true },
    added_by: { type: DataTypes.UUID, allowNull: false, references: { model: 'users', key: 'user_id' } },
    added_at: { type: DataTypes.DATE, allowNull: false, defaultValue: DataTypes.NOW },
    is_active: { type: DataTypes.BOOLEAN, allowNull: false, defaultValue: true },
  });

  await queryInterface.sequelize.query('CREATE INDEX IF NOT EXISTS "participants_request_id" ON "participants" ("request_id");');
  await queryInterface.sequelize.query('CREATE INDEX IF NOT EXISTS "participants_user_id" ON "participants" ("user_id");');
  await queryInterface.sequelize.query(`DO $$
  BEGIN
    IF NOT EXISTS (
      SELECT 1 FROM pg_constraint WHERE conname = 'uq_participants_request_user'
    ) THEN
      ALTER TABLE "participants" ADD CONSTRAINT "uq_participants_request_user" UNIQUE ("request_id", "user_id");
    END IF;
  END$$;`);
}

export async function down(queryInterface: QueryInterface): Promise<void> {
  await queryInterface.dropTable('participants');
  await queryInterface.sequelize.query('DROP TYPE IF EXISTS enum_participant_type;');
}


