CREATE TABLE IF NOT EXISTS product_change_log (
    id INT UNSIGNED AUTO_INCREMENT PRIMARY KEY,
    product_id INT UNSIGNED NOT NULL,
    user_id INT UNSIGNED NULL,
    change_type VARCHAR(64) NOT NULL,
    before_json JSON NULL,
    after_json JSON NULL,
    created_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,
    KEY product_change_log_product_idx (product_id),
    KEY product_change_log_user_idx (user_id),
    KEY product_change_log_created_idx (created_at),
    CONSTRAINT product_change_log_product_fk
        FOREIGN KEY (product_id) REFERENCES products(id)
        ON DELETE CASCADE ON UPDATE CASCADE,
    CONSTRAINT product_change_log_user_fk
        FOREIGN KEY (user_id) REFERENCES users(id)
        ON DELETE SET NULL ON UPDATE CASCADE
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;

CREATE TABLE IF NOT EXISTS sales_channels (
    id INT UNSIGNED AUTO_INCREMENT PRIMARY KEY,
    code VARCHAR(64) NOT NULL,
    name VARCHAR(128) NOT NULL,
    type VARCHAR(64) NOT NULL,
    status TINYINT(1) NOT NULL DEFAULT 1,
    created_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,
    updated_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
    UNIQUE KEY sales_channels_code_unique (code),
    KEY sales_channels_type_status_idx (type, status)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;

CREATE TABLE IF NOT EXISTS product_channel_map (
    id INT UNSIGNED AUTO_INCREMENT PRIMARY KEY,
    product_id INT UNSIGNED NOT NULL,
    channel_id INT UNSIGNED NOT NULL,
    external_product_id VARCHAR(128) NULL,
    external_variant_id VARCHAR(128) NULL,
    sync_state VARCHAR(32) NOT NULL DEFAULT 'not_linked',
    last_sync_at DATETIME NULL,
    created_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,
    updated_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
    KEY product_channel_map_product_idx (product_id),
    KEY product_channel_map_channel_idx (channel_id),
    KEY product_channel_map_sync_state_idx (sync_state),
    UNIQUE KEY product_channel_map_unique (product_id, channel_id, external_product_id, external_variant_id),
    CONSTRAINT product_channel_map_product_fk
        FOREIGN KEY (product_id) REFERENCES products(id)
        ON DELETE CASCADE ON UPDATE CASCADE,
    CONSTRAINT product_channel_map_channel_fk
        FOREIGN KEY (channel_id) REFERENCES sales_channels(id)
        ON DELETE CASCADE ON UPDATE CASCADE
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;
