-- Remove exact duplicate work logs so the next migration's unique index
-- (logged_hours_user_day_hours_project_desc_key) can be created without failing.
-- Same key expressions as that index; keeps the newest row of each group.
-- No-op when there are no duplicates (e.g. the index already exists).
DELETE l FROM `logged_hours` l
JOIN (
  SELECT `id` FROM (
    SELECT `id`,
           ROW_NUMBER() OVER (
             PARTITION BY `userId`,
                          DATE(DATE_ADD(`date`, INTERVAL 12 HOUR)),
                          CAST(ROUND(`hours` * 100) AS UNSIGNED),
                          IFNULL(`projectName`, ''),
                          LEFT(IFNULL(`description`, ''), 64)
             ORDER BY `createdAt` DESC, `id` DESC
           ) AS rn
    FROM `logged_hours`
  ) ranked
  WHERE ranked.rn > 1
) d ON d.`id` = l.`id`;
