ALTER TABLE queue_tickets
    ADD COLUMN personal_data_purged_at timestamptz,
    ALTER COLUMN phone_ciphertext DROP NOT NULL,
    ALTER COLUMN phone_nonce DROP NOT NULL,
    ALTER COLUMN phone_hmac DROP NOT NULL;

ALTER TABLE queue_tickets
    DROP CONSTRAINT queue_tickets_phone_nonce_check,
    DROP CONSTRAINT queue_tickets_phone_hmac_check,
    ADD CONSTRAINT queue_tickets_phone_pair_check CHECK (
        (phone_ciphertext IS NULL AND phone_nonce IS NULL AND phone_hmac IS NULL)
        OR (
            phone_ciphertext IS NOT NULL
            AND phone_nonce IS NOT NULL
            AND octet_length(phone_nonce) = 12
            AND phone_hmac IS NOT NULL
            AND phone_hmac ~ '^[0-9a-f]{64}$'
        )
    );

CREATE INDEX queue_tickets_personal_purge_idx
    ON queue_tickets (personal_data_purge_at, id)
    WHERE status IN ('COMPLETED', 'MISSED', 'CANCELED')
      AND personal_data_purged_at IS NULL;
