-- Fix for npm run db:sync failure:
-- Duplicate entry '1-0' for key 'users.uq_users_tenant_code'
--
-- Older builds created a users.user_code column and unique key uq_users_tenant_code.
-- Current User model does not use users.user_code, so Sequelize alter sync may drop
-- the column. MySQL can fail while rebuilding the old unique index if duplicate
-- tenant/user_code values already exist.

SET @db_name := DATABASE();
SET @index_exists := (
  SELECT COUNT(1)
  FROM INFORMATION_SCHEMA.STATISTICS
  WHERE TABLE_SCHEMA = @db_name
    AND TABLE_NAME = 'users'
    AND INDEX_NAME = 'uq_users_tenant_code'
);

SET @sql := IF(
  @index_exists > 0,
  'ALTER TABLE `users` DROP INDEX `uq_users_tenant_code`',
  'SELECT "uq_users_tenant_code index not found - skipped" AS message'
);

PREPARE stmt FROM @sql;
EXECUTE stmt;
DEALLOCATE PREPARE stmt;
