-- Fixes "the customer's first chat message says Not sent. Tap to retry".
--
-- Chats are per DELIVERY (unique index conversations_pair_delivery_uniq on
-- userOneId, userTwoId, deliveryRequestId). The live database still carries the
-- OLD per-PAIR unique index conversations_user_pair_uniq (userOneId, userTwoId)
-- from before that split. With it in place, two people who already chatted on
-- an earlier delivery can never get a thread for their next one: the insert
-- hits the old index, and every send on the new delivery fails with a 500.
--
-- helpers/messages_shared.php now removes this index by itself before it
-- creates the first per-delivery thread. This script does the same thing by
-- hand (phpMyAdmin > SQL tab), which is the quickest fix and does not depend
-- on the app's database user being allowed to ALTER tables. Safe to re-run.

SET @exists := (
    SELECT COUNT(*) FROM information_schema.STATISTICS
    WHERE table_schema = DATABASE()
      AND table_name = 'conversations'
      AND index_name = 'conversations_user_pair_uniq'
);
-- Says which case it hit, instead of a bare "1": with no database selected
-- in phpMyAdmin's left panel, DATABASE() is NULL and the check above looks
-- nowhere, which used to read exactly like "already fixed".
SET @ddl := IF(DATABASE() IS NULL,
    'SELECT ''NO DATABASE SELECTED: click izezmkaf_gudu in the left panel, then run this again'' AS result',
    IF(@exists > 0,
        'ALTER TABLE conversations DROP INDEX conversations_user_pair_uniq',
        'SELECT ''Nothing to do: the old one-chat-per-pair index is already gone'' AS result'));
PREPARE stmt FROM @ddl;
EXECUTE stmt;
DEALLOCATE PREPARE stmt;
