-- ===============================================================
--  STOCK TRANSFER DELIVERIES (EKSPEDISI)
-- ===============================================================

CREATE TABLE IF NOT EXISTS stock_transfer_deliveries (
    id BIGSERIAL PRIMARY KEY,
    stock_transfer_id BIGINT NOT NULL,
    supplier_id BIGINT,
    vehicle_plate VARCHAR(20),
    driver_name VARCHAR(100),
    document_number VARCHAR(50),
    document_path TEXT,
    shipping_cost_item NUMERIC(15,3),
    shipping_cost_total NUMERIC(15,3),
    created_at TIMESTAMPTZ DEFAULT NOW(),
    updated_at TIMESTAMPTZ DEFAULT NOW(),
    deleted_at TIMESTAMPTZ
);

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

    IF EXISTS (SELECT 1 FROM pg_tables WHERE tablename = 'suppliers') THEN
        ALTER TABLE stock_transfer_deliveries
            ADD CONSTRAINT fk_stock_transfer_deliveries_supplier
            FOREIGN KEY (supplier_id)
            REFERENCES suppliers(id)
            ON DELETE SET NULL ON UPDATE CASCADE;
    END IF;
END $$;

-- INDEXES
CREATE INDEX IF NOT EXISTS idx_stock_transfer_deliveries_transfer_id ON stock_transfer_deliveries(stock_transfer_id);
CREATE INDEX IF NOT EXISTS idx_stock_transfer_deliveries_supplier_id ON stock_transfer_deliveries(supplier_id);
