CREATE TABLE marketing_delivery_products (
    id BIGSERIAL PRIMARY KEY,
    marketing_product_id BIGINT UNIQUE NOT NULL,
    qty NUMERIC(15, 3) NOT NULL,
    unit_price NUMERIC(15, 3) NOT NULL,
    total_weight NUMERIC(15, 3) NOT NULL,
    avg_weight NUMERIC(15, 3) NOT NULL,
    total_price NUMERIC(15, 3) NOT NULL,
    delivery_date DATE,
    vehicle_number VARCHAR(50),
    created_at TIMESTAMPTZ DEFAULT NOW(),
    updated_at TIMESTAMPTZ DEFAULT NOW(),
    deleted_at TIMESTAMPTZ
);

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

CREATE INDEX idx_marketing_delivery_products_marketing_product_id ON marketing_delivery_products (marketing_product_id);

CREATE INDEX idx_marketing_delivery_products_delivery_date ON marketing_delivery_products (delivery_date);

CREATE INDEX idx_marketing_delivery_products_deleted_at ON marketing_delivery_products (deleted_at);