-- Remove duplicate earnings lines per tenant/order/clerk/type and add unique constraint

DELETE FROM `play_earnings_line`
WHERE `id` IN (
    SELECT dup_id FROM (
        SELECT id AS dup_id,
               ROW_NUMBER() OVER (
                   PARTITION BY tenant_id, order_id, clerk_id, earning_type
                   ORDER BY created_time, id
               ) AS rn
        FROM `play_earnings_line`
        WHERE deleted = 0
    ) ranked
    WHERE ranked.rn > 1
);

ALTER TABLE `play_earnings_line`
    ADD UNIQUE KEY `uk_tenant_order_clerk_type` (`tenant_id`, `order_id`, `clerk_id`, `earning_type`, `deleted`);
