-- Aktif ürünü olan slug'larda /listing yönlendirmesini kaldır (test vitrin migration yan etkisi).
-- idempotent

UPDATE routes r
INNER JOIN products p
  ON COALESCE(p.is_active, 1) = 1
  AND TRIM(COALESCE(p.slug, '')) <> ''
  AND r.locale = ''
  AND r.path = CONCAT('/', TRIM(p.slug))
SET r.redirect_to = NULL,
    r.redirect_status = 301,
    r.entity_id = p.id,
    r.type = 'product',
    r.is_active = 1,
    r.updated_at = CURRENT_TIMESTAMP
WHERE TRIM(COALESCE(r.redirect_to, '')) = '/listing';

UPDATE routes r
INNER JOIN products p
  ON COALESCE(p.is_active, 1) = 1
  AND TRIM(COALESCE(p.slug, '')) <> ''
  AND r.locale = ''
  AND r.path = CONCAT('/urun/', TRIM(p.slug))
SET r.redirect_to = CONCAT('/', TRIM(p.slug)),
    r.redirect_status = 301,
    r.entity_id = NULL,
    r.type = 'product',
    r.is_active = 1,
    r.updated_at = CURRENT_TIMESTAMP
WHERE TRIM(COALESCE(r.redirect_to, '')) = '/listing';

INSERT INTO routes (locale, path, type, entity_id, redirect_to, redirect_status, is_active, priority)
SELECT '', CONCAT('/', TRIM(p.slug)), 'product', p.id, NULL, 301, 1, 30
FROM products p
WHERE COALESCE(p.is_active, 1) = 1
  AND TRIM(COALESCE(p.slug, '')) <> ''
  AND NOT EXISTS (
    SELECT 1 FROM routes r WHERE r.locale = '' AND r.path = CONCAT('/', TRIM(p.slug))
  );
