-- Idempotent: pasif test ürün slug'ları → /listing (301). Aktif ürün slug'ına dokunma.
-- resolve.php zincir redirect + Next permanentRedirect ile adres çubuğu /listing olur.

UPDATE routes r
SET r.redirect_to = '/listing',
    r.redirect_status = 301,
    r.entity_id = NULL,
    r.type = 'product',
    r.is_active = 1,
    r.updated_at = CURRENT_TIMESTAMP
WHERE r.locale = ''
  AND r.path IN (
    '/veysel-test-2',
    '/veysel-test-tr',
    '/veysel-test',
    '/veysel2',
    '/urun/veysel-test-2',
    '/urun/veysel-test-tr',
    '/urun/veysel-test',
    '/urun/veysel2'
  )
  AND NOT EXISTS (
    SELECT 1
    FROM products p
    WHERE COALESCE(p.is_active, 1) = 1
      AND TRIM(COALESCE(p.slug, '')) <> ''
      AND (
        CONCAT('/', TRIM(p.slug)) = r.path
        OR CONCAT('/urun/', TRIM(p.slug)) = r.path
      )
  );

INSERT INTO routes (locale, path, type, entity_id, redirect_to, redirect_status, is_active, priority)
SELECT '', p.path, 'product', NULL, '/listing', 301, 1, 30
FROM (
  SELECT '/veysel-test-2' AS path
  UNION ALL SELECT '/veysel-test-tr'
  UNION ALL SELECT '/veysel-test'
  UNION ALL SELECT '/veysel2'
  UNION ALL SELECT '/urun/veysel-test-2'
  UNION ALL SELECT '/urun/veysel-test-tr'
  UNION ALL SELECT '/urun/veysel-test'
  UNION ALL SELECT '/urun/veysel2'
) AS p
WHERE NOT EXISTS (
  SELECT 1 FROM routes r WHERE r.locale = '' AND r.path = p.path
)
AND NOT EXISTS (
  SELECT 1
  FROM products pr
  WHERE COALESCE(pr.is_active, 1) = 1
    AND TRIM(COALESCE(pr.slug, '')) <> ''
    AND (
      CONCAT('/', TRIM(pr.slug)) = p.path
      OR CONCAT('/urun/', TRIM(pr.slug)) = p.path
    )
);
