CREATE TABLE IF NOT EXISTS purchase_items (
    id BIGSERIAL PRIMARY KEY,
    purchase_id BIGINT NOT NULL,
    product_id BIGINT NOT NULL,
    warehouse_id BIGINT NOT NULL,
    product_warehouse_id BIGINT,
    received_date TIMESTAMPTZ,
    travel_number VARCHAR,
    travel_number_docs VARCHAR,
    vehicle_number VARCHAR,
    sub_qty NUMERIC(15, 3) NOT NULL,
    total_qty NUMERIC(15, 3) NOT NULL DEFAULT 0,
    total_used NUMERIC(15, 3) NOT NULL DEFAULT 0,
    price NUMERIC(15, 3) NOT NULL DEFAULT 0,
    total_price NUMERIC(15, 3) NOT NULL DEFAULT 0,
    CONSTRAINT uq_purchase_items_purchase_product_warehouse
        UNIQUE (purchase_id, product_id, warehouse_id)
);

DO $$
BEGIN
    IF EXISTS (SELECT 1 FROM pg_tables WHERE tablename = 'products') THEN
        EXECUTE
        'ALTER TABLE purchase_items
         ADD CONSTRAINT fk_purchase_items_product
         FOREIGN KEY (product_id)
         REFERENCES products(id)
         ON DELETE RESTRICT ON UPDATE CASCADE';
    END IF;

    IF EXISTS (SELECT 1 FROM pg_tables WHERE tablename = 'warehouses') THEN
        EXECUTE
        'ALTER TABLE purchase_items
         ADD CONSTRAINT fk_purchase_items_warehouse
         FOREIGN KEY (warehouse_id)
         REFERENCES warehouses(id)
         ON DELETE RESTRICT ON UPDATE CASCADE';
    END IF;

    IF EXISTS (SELECT 1 FROM pg_tables WHERE tablename = 'product_warehouses') THEN
        EXECUTE
        'ALTER TABLE purchase_items
         ADD CONSTRAINT fk_purchase_items_product_warehouse
         FOREIGN KEY (product_warehouse_id)
         REFERENCES product_warehouses(id)
         ON DELETE SET NULL ON UPDATE CASCADE';
    END IF;

END $$;

CREATE INDEX IF NOT EXISTS idx_purchase_items_product_id ON purchase_items (product_id);
CREATE INDEX IF NOT EXISTS idx_purchase_items_warehouse_id ON purchase_items (warehouse_id);
CREATE INDEX IF NOT EXISTS idx_purchase_items_product_warehouse_id ON purchase_items (product_warehouse_id);
CREATE INDEX IF NOT EXISTS idx_purchase_items_purchase_id ON purchase_items (purchase_id);
