-- Delete duplicate offers per product per feed, keeping the one with most sizes (or lowest price as tiebreaker)
DELETE FROM product_offers
WHERE id IN (
    SELECT id FROM (
        SELECT id,
            ROW_NUMBER() OVER (
                PARTITION BY product_id, feed_id
                ORDER BY jsonb_array_length(COALESCE(sizes, '[]'::jsonb)) DESC, price ASC, id ASC
            ) as rn
        FROM product_offers
    ) ranked
    WHERE rn > 1
);

-- Also merge sizes from deleted duplicates would be ideal, but complex.
-- For now, just keep the best offer per product per feed.

-- Verify
SELECT COUNT(*) as remaining_dups FROM (
  SELECT product_id, feed_id, COUNT(*) as c
  FROM product_offers
  GROUP BY product_id, feed_id
  HAVING COUNT(*) > 1
) sub;
