CREATE TABLE IF NOT EXISTS product_integration_translations (
    id INT UNSIGNED AUTO_INCREMENT PRIMARY KEY,
    product_id INT UNSIGNED NOT NULL,
    integration_id INT UNSIGNED NOT NULL,
    -- NULL means "inherit from product_translations" for this integration
    name VARCHAR(255) NULL,
    short_description TEXT NULL,
    description LONGTEXT NULL,
    created_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,
    updated_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
    UNIQUE KEY pit_product_integration_unique (product_id, integration_id),
    CONSTRAINT pit_product_fk
        FOREIGN KEY (product_id) REFERENCES products(id)
        ON DELETE CASCADE ON UPDATE CASCADE,
    CONSTRAINT pit_integration_fk
        FOREIGN KEY (integration_id) REFERENCES integrations(id)
        ON DELETE CASCADE ON UPDATE CASCADE
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;

-- Migrate existing products to marianek.pl integration.
-- Finds the integration by name 'marianek.pl' and copies current
-- product_translations content for all linked products.
INSERT INTO product_integration_translations
    (product_id, integration_id, name, short_description, description, created_at, updated_at)
SELECT
    pt.product_id,
    i.id AS integration_id,
    pt.name,
    pt.short_description,
    pt.description,
    NOW(),
    NOW()
-- NOTE: pcm.integration_id was added in migration 000007 (ALTER TABLE).
-- If no product_channel_map rows have integration_id set, this inserts 0 rows (safe).
FROM product_translations pt
INNER JOIN product_channel_map pcm ON pcm.product_id = pt.product_id
INNER JOIN integrations i ON i.id = pcm.integration_id
WHERE i.name = 'marianek.pl'
  AND pt.lang = 'pl'
ON DUPLICATE KEY UPDATE
    name = VALUES(name),
    short_description = VALUES(short_description),
    description = VALUES(description),
    updated_at = VALUES(updated_at);
