-- Run once on an existing database that already has `products` (adds gallery without re-seeding).
-- Example: mysql -u USER -p DB_NAME < database/add_product_images.sql

CREATE TABLE IF NOT EXISTS product_images (
  id INT UNSIGNED NOT NULL AUTO_INCREMENT,
  product_id INT UNSIGNED NOT NULL,
  sort_order INT NOT NULL DEFAULT 0,
  image_path VARCHAR(512) NOT NULL,
  PRIMARY KEY (id),
  KEY idx_product_images_product (product_id),
  CONSTRAINT fk_product_images_product FOREIGN KEY (product_id) REFERENCES products (id) ON DELETE CASCADE
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;

-- Copy legacy cover into gallery when a product has no gallery rows yet.
INSERT INTO product_images (product_id, sort_order, image_path)
SELECT p.id, 0, p.image_path
FROM products p
WHERE p.image_path <> ''
  AND NOT EXISTS (
    SELECT 1 FROM product_images pi WHERE pi.product_id = p.id
  );
