CREATE TABLE marketing_products (
    id BIGSERIAL PRIMARY KEY,
    marketing_id BIGINT NOT NULL,
    product_warehouse_id BIGINT NOT NULL,
    qty NUMERIC(15, 3) NOT NULL,
    unit_price NUMERIC(15, 3) NOT NULL,
    avg_weight NUMERIC(15, 3) NOT NULL,
    total_weight NUMERIC(15, 3) NOT NULL,
    total_price NUMERIC(15, 3) NOT NULL,
    created_at TIMESTAMPTZ DEFAULT NOW(),
    updated_at TIMESTAMPTZ DEFAULT NOW(),
    deleted_at TIMESTAMPTZ
);

DO $$
BEGIN
    IF EXISTS (SELECT 1 FROM pg_tables WHERE tablename = 'marketings') THEN
        ALTER TABLE marketing_products
            ADD CONSTRAINT fk_marketing_products_marketing_id 
            FOREIGN KEY (marketing_id) REFERENCES marketings(id) ON DELETE CASCADE;
    END IF;

    IF EXISTS (SELECT 1 FROM pg_tables WHERE tablename = 'product_warehouses') THEN
        ALTER TABLE marketing_products
            ADD CONSTRAINT fk_marketing_products_product_warehouse_id 
            FOREIGN KEY (product_warehouse_id) REFERENCES product_warehouses(id) ON DELETE RESTRICT;
    END IF;
END $$;

CREATE INDEX idx_marketing_products_marketing_id ON marketing_products (marketing_id);

CREATE INDEX idx_marketing_products_product_warehouse_id ON marketing_products (product_warehouse_id);

CREATE INDEX idx_marketing_products_deleted_at ON marketing_products (deleted_at);