SET @ddl = (
  SELECT IF(
    EXISTS(
      SELECT 1
      FROM INFORMATION_SCHEMA.STATISTICS
      WHERE TABLE_SCHEMA = DATABASE()
        AND TABLE_NAME = 'teams'
        AND INDEX_NAME = 'idx_teams_law_firm'
    ),
    'SELECT 1',
    'ALTER TABLE teams ADD KEY idx_teams_law_firm (law_firm_id)'
  )
);
PREPARE stmt FROM @ddl;
EXECUTE stmt;
DEALLOCATE PREPARE stmt;

SET @ddl = (
  SELECT IF(
    EXISTS(
      SELECT 1
      FROM INFORMATION_SCHEMA.STATISTICS
      WHERE TABLE_SCHEMA = DATABASE()
        AND TABLE_NAME = 'teams'
        AND INDEX_NAME = 'uq_teams_law_firm'
    ),
    'ALTER TABLE teams DROP INDEX uq_teams_law_firm',
    'SELECT 1'
  )
);
PREPARE stmt FROM @ddl;
EXECUTE stmt;
DEALLOCATE PREPARE stmt;

SET @ddl = (
  SELECT IF(
    EXISTS(
      SELECT 1
      FROM INFORMATION_SCHEMA.STATISTICS
      WHERE TABLE_SCHEMA = DATABASE()
        AND TABLE_NAME = 'team_memberships'
        AND INDEX_NAME = 'idx_team_memberships_law_firm_user'
    ),
    'SELECT 1',
    'ALTER TABLE team_memberships ADD KEY idx_team_memberships_law_firm_user (law_firm_id, user_id)'
  )
);
PREPARE stmt FROM @ddl;
EXECUTE stmt;
DEALLOCATE PREPARE stmt;

SET @ddl = (
  SELECT IF(
    EXISTS(
      SELECT 1
      FROM INFORMATION_SCHEMA.STATISTICS
      WHERE TABLE_SCHEMA = DATABASE()
        AND TABLE_NAME = 'team_memberships'
        AND INDEX_NAME = 'uq_team_memberships_law_firm_user'
    ),
    'ALTER TABLE team_memberships DROP INDEX uq_team_memberships_law_firm_user',
    'SELECT 1'
  )
);
PREPARE stmt FROM @ddl;
EXECUTE stmt;
DEALLOCATE PREPARE stmt;

SET @ddl = (
  SELECT IF(
    EXISTS(
      SELECT 1
      FROM INFORMATION_SCHEMA.STATISTICS
      WHERE TABLE_SCHEMA = DATABASE()
        AND TABLE_NAME = 'team_agents'
        AND INDEX_NAME = 'idx_team_agents_law_firm_user'
    ),
    'SELECT 1',
    'ALTER TABLE team_agents ADD KEY idx_team_agents_law_firm_user (law_firm_id, user_id)'
  )
);
PREPARE stmt FROM @ddl;
EXECUTE stmt;
DEALLOCATE PREPARE stmt;

SET @ddl = (
  SELECT IF(
    EXISTS(
      SELECT 1
      FROM INFORMATION_SCHEMA.STATISTICS
      WHERE TABLE_SCHEMA = DATABASE()
        AND TABLE_NAME = 'team_agents'
        AND INDEX_NAME = 'uq_team_agents_law_firm_user'
    ),
    'ALTER TABLE team_agents DROP INDEX uq_team_agents_law_firm_user',
    'SELECT 1'
  )
);
PREPARE stmt FROM @ddl;
EXECUTE stmt;
DEALLOCATE PREPARE stmt;
