-- ===============================================================
--  STOCK TRANSFER DELIVERY ITEMS (PIVOT)
-- ===============================================================

CREATE TABLE IF NOT EXISTS stock_transfer_delivery_items (
    id BIGSERIAL PRIMARY KEY,
    stock_transfer_delivery_id BIGINT NOT NULL,
    stock_transfer_detail_id BIGINT NOT NULL,
    quantity NUMERIC(15, 3) NOT NULL CHECK (quantity > 0)
);

-- FOREIGN KEYS
DO $$
BEGIN
    IF EXISTS (SELECT 1 FROM pg_tables WHERE tablename = 'stock_transfer_deliveries') THEN
        ALTER TABLE stock_transfer_delivery_items
            ADD CONSTRAINT fk_delivery_items_delivery
            FOREIGN KEY (stock_transfer_delivery_id)
            REFERENCES stock_transfer_deliveries(id)
            ON DELETE CASCADE ON UPDATE CASCADE;
    END IF;

    IF EXISTS (SELECT 1 FROM pg_tables WHERE tablename = 'stock_transfer_details') THEN
        ALTER TABLE stock_transfer_delivery_items
            ADD CONSTRAINT fk_delivery_items_detail
            FOREIGN KEY (stock_transfer_detail_id)
            REFERENCES stock_transfer_details(id)
            ON DELETE CASCADE ON UPDATE CASCADE;
    END IF;
END $$;

-- INDEXES
CREATE INDEX IF NOT EXISTS idx_stock_transfer_delivery_items_delivery_id ON stock_transfer_delivery_items (stock_transfer_delivery_id);

CREATE INDEX IF NOT EXISTS idx_stock_transfer_delivery_items_detail_id ON stock_transfer_delivery_items (stock_transfer_detail_id);