CREATE TABLE IF NOT EXISTS product_variants (
    id INT UNSIGNED AUTO_INCREMENT PRIMARY KEY,
    product_id INT UNSIGNED NOT NULL,
    permutation_hash VARCHAR(191) NOT NULL,
    sku VARCHAR(128) NULL,
    ean VARCHAR(32) NULL,
    status TINYINT(1) NOT NULL DEFAULT 1,
    price_brutto DECIMAL(12,2) NULL,
    price_brutto_promo DECIMAL(12,2) NULL,
    price_netto DECIMAL(12,2) NULL,
    price_netto_promo DECIMAL(12,2) NULL,
    weight DECIMAL(10,3) NULL,
    created_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,
    updated_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
    UNIQUE KEY product_variants_sku_unique (sku),
    UNIQUE KEY product_variants_product_permutation_unique (product_id, permutation_hash),
    KEY product_variants_product_idx (product_id),
    KEY product_variants_status_idx (status),
    CONSTRAINT product_variants_product_fk
        FOREIGN KEY (product_id) REFERENCES products(id)
        ON DELETE CASCADE ON UPDATE CASCADE
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;

CREATE TABLE IF NOT EXISTS product_variant_attributes (
    variant_id INT UNSIGNED NOT NULL,
    attribute_id INT UNSIGNED NOT NULL,
    value_id INT UNSIGNED NOT NULL,
    created_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,
    PRIMARY KEY (variant_id, attribute_id),
    KEY product_variant_attributes_value_idx (value_id),
    CONSTRAINT product_variant_attributes_variant_fk
        FOREIGN KEY (variant_id) REFERENCES product_variants(id)
        ON DELETE CASCADE ON UPDATE CASCADE,
    CONSTRAINT product_variant_attributes_attribute_fk
        FOREIGN KEY (attribute_id) REFERENCES attributes(id)
        ON DELETE RESTRICT ON UPDATE CASCADE,
    CONSTRAINT product_variant_attributes_value_fk
        FOREIGN KEY (value_id) REFERENCES attribute_values(id)
        ON DELETE RESTRICT ON UPDATE CASCADE
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;
